【问题标题】:Using service in Pact consumer test with Java EE使用 Java EE 在 Pact 消费者测试中使用服务
【发布时间】:2020-12-22 11:25:26
【问题描述】:

我想在我们的 Java EE 应用程序中实现 Pact 消费者测试。该测试将调用一个消费者服务方法,该方法将触发实际的 REST 调用。

这是迄今为止的 Pact 测试:

@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "my-service")
public class MyServiceConsumerTest {

    @Inject
    private MyService myService;

    @Pact(consumer = "myConsumer")
    public RequestResponsePact mail(PactDslWithProvider builder) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", ContentType.getJSON().asString());

        PactDslJsonBody jsonBody = new PactDslJsonBody()
                .stringValue("emailAddress", "foo@bar.com")
                .stringValue("subject", "Test subject")
                .stringValue("content", "Test content")
                .asBody();

        return builder
                .given("DEFAULT_STATE")
                .uponReceiving("request for sending a mail")
                    .path("/mail")
                    .method("POST")
                    .headers(headers)
                    .body(jsonBody)
                .willRespondWith()
                    .status(Response.Status.OK.getStatusCode())
                .toPact();
    }

    @Test
    @PactTestFor(pactMethod = "mail")
    public void sendMail() {
        MailNotification mailNotification = MailNotification.builder()
                .emailAddress("foo@bar.com")
                .subject("Test subject")
                .content("Test content")
                .build();
        myService.sendNotification(mailNotification);
    }
}

有趣的是这一行:

myService.sendNotification(mailNotification);

当我运行消费者单元测试时,MyService 的注入不起作用,即导致myService 成为null。此外,我认为有必要告诉服务向 Pact 模拟服务器发送其请求?

当然,我可以在测试中触发最终的 REST 请求,但这会忽略服务逻辑。

我想我在这里遗漏了什么?

【问题讨论】:

    标签: pact pact-jvm


    【解决方案1】:

    是的,您应该在@PactVerification 测试中访问模拟服务器。不要在没有实际应用程序代码的情况下触发,以防将来发生更改。如果您更改该请求的 HTTP 属性,测试应该会失败

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-20
      • 2020-10-22
      • 1970-01-01
      • 2017-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多