无法在pact提供程序测试中使用mockito模拟服务层

wpx232ag  于 2024-01-07  发布在  其他
关注(0)|答案(1)|浏览(150)

我正在尝试为我的API实现契约测试。我能够在消费端定义合约并将其上传到Pact broker。在我的提供者API上,我已经从broker获取了合约,但在尝试验证合约时,我的测试失败了,因为服务层正在执行而不是被存根-这反过来导致ResourceNotFoundException: Client client1 with app myapp not found-如果在数据库中找不到client,则引发自定义异常。

  1. @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  2. @ExtendWith(SpringExtension.class)
  3. @Provider("lockedOut_identityService")
  4. @PactBroker(url = "http://localhost:9292")
  5. @ExtendWith(MockitoExtension.class)
  6. public class AuthServiceProviderTest {
  7. @Mock
  8. private ClientService clientService;
  9. @Value("${local.server.port}")
  10. private int port;
  11. @BeforeEach
  12. void before(PactVerificationContext context) {
  13. context.setTarget(new HttpTestTarget("localhost", port, "/"));
  14. }
  15. @TestTemplate
  16. @ExtendWith(PactVerificationInvocationContextProvider.class)
  17. void pactVerificationTestTemplate(PactVerificationContext context) {
  18. if (context != null) {
  19. context.verifyInteraction();
  20. }
  21. }
  22. @State("Get client by appName & clientId")
  23. public void getClient() {
  24. when(clientService.getClient(eq(null), any(String.class), any(String.class)))
  25. .thenReturn(ClientResponse.builder()
  26. .id(1L)
  27. .clientId("client1")
  28. .clientSecret("secret")
  29. .authMethod(null)
  30. .authGrantType(null)
  31. .redirectUri("redirectUri")
  32. .createdAt(LocalDateTime.now())
  33. .build());
  34. }
  35. }

字符串
看起来好像when(clientService.getClient(eq(null), any(String.class), any(String.class)))实际上并没有覆盖服务层。
控制器:

  1. @GetMapping("/get-client")
  2. public ResponseEntity<ClientResponse> getClient(
  3. @RequestHeader(value = "x-correlation-id", required = true) String correlationId,
  4. @RequestParam(value = "id", required = false) Long id,
  5. @RequestParam(value = "appName", required = false) String appName,
  6. @RequestParam(value = "clientId", required = false) String clientId
  7. ) {
  8. if ((id == null && appName != null && clientId == null)
  9. || (id == null && appName == null)) {
  10. throw new InvalidRequestException(ErrorConstant.INVALID_REQUEST.getValue());
  11. }
  12. return new ResponseEntity<>(clientService.getClient(id, appName, clientId), HttpStatus.OK);
  13. }


使用以下值调用控制器端点:id:null,appname:“myapp”,clientId:“client 1”
我错过了什么?看起来从Mockito结束,事情看起来很好。我错过了任何额外的契约配置使用Mockito插件?
使用依赖项:

  1. implementation 'au.com.dius.pact.provider:junit5:4.6.3'

sdnqo3pr

sdnqo3pr1#

如果你使用的是@SpringBootTest,你需要用@MockBean来注解mocked对象,以将它们注入Spring上下文。这意味着Spring创建的bean将使用你的@MockBean作为它们的依赖项。
参见Difference between @Mock, @MockBean and Mockito.mock()

相关问题