pact与springboot

pcww981p  于 2021-06-30  发布在  Java
关注(0)|答案(0)|浏览(228)

我试着用springboot来学习baeldung pact教程
https://www.baeldung.com/pact-junit-consumer-driven-contracts
我的服务中有一个get和一个post方法,如下所示:

public class BaeldungTest {
    @Rule
    public PactProviderRuleMk2 mockProvider
    = new PactProviderRuleMk2("test_provider", "localhost", 8080, this);

    @Pact(consumer = "test_consumer")
    public RequestResponsePact createPactGet(PactDslWithProvider builder) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");

        return builder
          .given("test GET")
            .uponReceiving("GET REQUEST")
            .path("/pact")
            .method("GET")
          .willRespondWith()
            .status(200)
            .headers(headers)
            .body("{\"condition\": true, \"name\": \"tom\"}")
           .given("test POST")
           .uponReceiving("POST REQUEST")
             .method("POST")
             .headers(headers)
             .body("{\"name\": \"Michael\"}")
              .path("/create")
            .willRespondWith()
              .status(201)
              .headers(headers)
              .body("")
            .toPact();

    }

@Test
@PactVerification()
public void GETRequestTest_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {

        // when
        ResponseEntity<String> response = new RestTemplate()
          .getForEntity(mockProvider.getUrl() + "/pact", String.class);      
        // then
        assertEquals(200,response.getStatusCode().value());
        assertTrue(response.getHeaders().get("Content-Type").contains("application/json"));

    }

    @Test
    @PactVerification()
    public void POSTRequestTest_whenSendRequest_shouldReturn201WithProperHeaderAndBody() {

        // when
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        String jsonBody = "{\"name\": \"Michael\"}";

       // when
       ResponseEntity<String> postResponse = new RestTemplate()
      .exchange(
        mockProvider.getUrl() + "/create",
        HttpMethod.POST,
        new HttpEntity<String>(jsonBody, httpHeaders), 
        String.class
      );

    //then
    assertEquals(201, postResponse.getStatusCode().value());          
    }

 }

现在,如果我运行get服务测试,就会得到一个错误:post请求没有收到

au.com.dius.pact.consumer.PactMismatchesException: The following requests were not received:
    method: POST
    path: /create
    query: [:]
    headers: [Content-Type:application/json]
    ...

对于post测试,我得到未收到get请求的错误:au.com.dius.pact.consumer.pactmismatchesexception:未收到以下请求:method:post path:/create query:[:]headers:[content]-type:application/json]
如何解决这个问题?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题