我想在我们的 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 请求,但这会忽略服务逻辑。
我想我在这里遗漏了什么?