我正在尝试为我的API实现契约测试。我能够在消费端定义合约并将其上传到Pact broker。在我的提供者API上,我已经从broker获取了合约,但在尝试验证合约时,我的测试失败了,因为服务层正在执行而不是被存根-这反过来导致ResourceNotFoundException: Client client1 with app myapp not found
-如果在数据库中找不到client
,则引发自定义异常。
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(SpringExtension.class)
@Provider("lockedOut_identityService")
@PactBroker(url = "http://localhost:9292")
@ExtendWith(MockitoExtension.class)
public class AuthServiceProviderTest {
@Mock
private ClientService clientService;
@Value("${local.server.port}")
private int port;
@BeforeEach
void before(PactVerificationContext context) {
context.setTarget(new HttpTestTarget("localhost", port, "/"));
}
@TestTemplate
@ExtendWith(PactVerificationInvocationContextProvider.class)
void pactVerificationTestTemplate(PactVerificationContext context) {
if (context != null) {
context.verifyInteraction();
}
}
@State("Get client by appName & clientId")
public void getClient() {
when(clientService.getClient(eq(null), any(String.class), any(String.class)))
.thenReturn(ClientResponse.builder()
.id(1L)
.clientId("client1")
.clientSecret("secret")
.authMethod(null)
.authGrantType(null)
.redirectUri("redirectUri")
.createdAt(LocalDateTime.now())
.build());
}
}
字符串
看起来好像when(clientService.getClient(eq(null), any(String.class), any(String.class)))
实际上并没有覆盖服务层。
控制器:
@GetMapping("/get-client")
public ResponseEntity<ClientResponse> getClient(
@RequestHeader(value = "x-correlation-id", required = true) String correlationId,
@RequestParam(value = "id", required = false) Long id,
@RequestParam(value = "appName", required = false) String appName,
@RequestParam(value = "clientId", required = false) String clientId
) {
if ((id == null && appName != null && clientId == null)
|| (id == null && appName == null)) {
throw new InvalidRequestException(ErrorConstant.INVALID_REQUEST.getValue());
}
return new ResponseEntity<>(clientService.getClient(id, appName, clientId), HttpStatus.OK);
}
型
使用以下值调用控制器端点:id:null,appname:“myapp”,clientId:“client 1”
我错过了什么?看起来从Mockito结束,事情看起来很好。我错过了任何额外的契约配置使用Mockito插件?
使用依赖项:
implementation 'au.com.dius.pact.provider:junit5:4.6.3'
型
1条答案
按热度按时间sdnqo3pr1#
如果你使用的是
@SpringBootTest
,你需要用@MockBean
来注解mocked对象,以将它们注入Spring上下文。这意味着Spring创建的bean将使用你的@MockBean作为它们的依赖项。参见Difference between @Mock, @MockBean and Mockito.mock()