Spring Cloud Contract Consumer Test Issue

时间:2017-05-10 08:23:07

标签: spring-cloud-contract

我正在测试Spring云合约的消费者方面。

提供商在这里:https://github.com/pkid/spring-cloud-contract-with-surefire

从提供者生成的存根jar在这里:https://github.com/pkid/spring-cloud-contract-with-surefire-consumer/blob/master/sample-repo-service-1.0.0-SNAPSHOT-stubs.jar

当我运行消费者测试时(来源在这里: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!\"}"));
}

当我执行" mvn test"时,我可以看到存根jar正确找到并解压缩。但是我得到了端点2" / greeting"不存在(404)。

你能帮帮我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您正在使用mockMvc连接到WireMock实例。那不行。将消费者方mockMvc更改为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!\"}");
    }

}

请在文档http://docs.spring.io/spring-security/site/docs/current/reference/html/test-mockmvc.html

中阅读模拟mvc的内容