0

我正在测试 Spring Cloud 合约的消费者端。

提供者在这里: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。罐

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

请你帮助我好吗?谢谢!

4

1 回答 1

3

您正在使用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中的 mock mvc 是什么

于 2017-05-10T08:45:45.283 回答