0

我想在我们的 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 请求,但这会忽略服务逻辑。

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

4

1 回答 1

0

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

于 2020-11-20T20:41:53.253 回答