如何使用 PactVerificationSpringProvider 和 Junit5 为协议提供程序测试添加标头?

问题描述

我正在尝试使用 junit5spring 编写契约提供者测试。

目前我得到了例外:

1) Verifying a pact between external-service and my-app - includes headers "Content-Type" with value "[application/json]"

    1.1) header: Expected a header 'Content-Type' but was missing

我应该如何添加标题? 我已经这样试过了:

@TestTemplate
    @ExtendWith(PactVerificationspringProvider.class)
    public void pactVerificationTestTemplate(PactVerificationContext context,HttpRequest request) {
        request.addHeader("Content-Type","application/json");

        if (context != null) {
            context.verifyInteraction();
        }
    }

但它也不起作用:

org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [org.apache.http.HttpRequest request] in method [public void com.swisscom.abusehq.anonymizer.pact.PactProviderTest.pactVerificationTestTemplate(au.com.dius.pact.provider.junit5.PactVerificationContext,org.apache.http.HttpRequest)].

全班:

@ActiveProfiles("test")
@ExtendWith(SpringExtension.class)
@SpringBoottest(webEnvironment = SpringBoottest.WebEnvironment.DEFINED_PORT)
@ContextConfiguration(classes = {MyTestConfiguration.class})
@Provider("my-app")
@Pactbroker
        (
                consumerVersionSelectors = @VersionSelector(tag = "developer-build"),authentication = @PactbrokerAuth(
                        username = "${pactbroker.auth.username}",password = "${pactbroker.auth.password}"
                )
        )
@Slf4j
public class PactProviderTest {

    @InjectMocks
    MyController myController;

    @Mock
    MyService myService;

    @TestTemplate
    @ExtendWith(PactVerificationspringProvider.class)
    public void pactVerificationTestTemplate(PactVerificationContext context,"application/json");

        if (context != null) {
            context.verifyInteraction();
        }
    }

    @BeforeEach
    void before(PactVerificationContext context) {
        MockitoAnnotations.initMocks(this);
        mockmvcTestTarget target = new mockmvcTestTarget();
        target.setControllers(myController);
        context.setTarget(target);
    }

    @State("account exists")
    public void notificationForAccount(Map data) {
        log.info("Now service in 'state 1' state: " + data);

        donothing().when(myService).sendNotification(any(MyRequest.class));
    }

}

解决方法

1.1) header: Expected a header 'Content-Type' but was missing

此消息来自提供者端的响应验证。它告诉协议期望服务器返回 Content-Type 标头,但它没有。您的应用程序应为此和测试进行调整,即 @RestController 或其他内容:

@RequestMapping(value = "/my/url",produces = { "application/json" }