Search code examples
spring-cloud-contract

Spring Cloud Contract Consumer Test Issue


I am testing the consumer side of the spring cloud contract.

The provider is here: https://github.com/pkid/spring-cloud-contract-with-surefire.

The stubs jar generated from the provider is here: https://github.com/pkid/spring-cloud-contract-with-surefire-consumer/blob/master/sample-repo-service-1.0.0-SNAPSHOT-stubs.jar

When I run the consumer test(source is here: https://github.com/pkid/spring-cloud-contract-with-surefire-consumer):

@Test
public void shouldGiveFreeSubscriptionForFriends() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/greeting")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().string("{\"id\":1,\"content\":\"Hello, World!\"}"));
}

When I do "mvn test", I can see that the stubs jar is correctly found and unpacked. However I got the error that the endpoint 2 "/greeting" does not exist(404).

Could you please help me? Thank you!


Solution

  • You are using mockMvc to connect to a WireMock instance. That won't work. Change mockMvc on the consumer side to a restTemplate

    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = WebEnvironment.MOCK)
    @AutoConfigureMockMvc
    @AutoConfigureJsonTesters
    @DirtiesContext
    @AutoConfigureStubRunner(ids = {"com.sap.ngp.test:sample-repo-service:+:stubs:8080"}, workOffline = true)
    public class ConsumerTest {
    
        @Test
        public void shouldGiveFreeSubscriptionForFriends() throws Exception {
            ResponseEntity<String> result = new TestRestTemplate().exchange(RequestEntity
                .get(URI.create("http://localhost:8080/greeting"))
                .header("Content-Type", MediaType.APPLICATION_JSON_VALUE)
                .build(), String.class);
    
            BDDAssertions.then(result.getStatusCode().value()).isEqualTo(200);
            BDDAssertions.then(result.getBody()).isEqualTo("{\"content\":\"Hello, World!\"}");
        }
    
    }
    

    Please read what mock mvc is for in the docs http://docs.spring.io/spring-security/site/docs/current/reference/html/test-mockmvc.html