Spring Cloud Contract WireMock
使用Spring Cloud Contract WireMock模块,您可以在Spring Boot应用程序中使用WireMock。查看 示例 以获取更多详细信息。
如果您有一个Spring Boot应用程序,该应用程序使用Tomcat作为嵌入式服务器(这是spring-boot-starter-web的默认设置),则可以将spring-cloud-starter-contract-stub-runner添加到您的类路径中,并添加@AutoConfigureWireMock,以便能够在测试中使用Wiremock。Wiremock作为存根服务器运行,您可以在测试中使用Java API或通过静态JSON声明来注册存根行为。以下代码显示了一个示例:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureWireMock(port = 0)
public class WiremockForDocsTests {
// A service that calls out over HTTP
@Autowired
private Service service;
@Before
public void setup() {
this.service.setBase("http://localhost:"
+ this.environment.getProperty("wiremock.server.port"));
}
// Using the WireMock APIs in the normal way:
@Test
public void contextLoads() throws Exception {
// Stubbing WireMock
stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
// We're asserting if WireMock responded properly
assertThat(this.service.go()).isEqualTo("Hello World!");
}
}要在其他端口上启动存根服务器,请使用@AutoConfigureWireMock(port=9999)。对于随机端口,请使用值0。可以在测试应用程序上下文中使用“ wiremock.server.port”属性绑定存根服务器端口。使用@AutoConfigureWireMock将类型为WiremockConfiguration的bean添加到测试应用程序上下文中,该变量将被缓存在具有相同上下文的方法和类之间,与Spring集成测试相同。您也可以将WireMockServer类型的bean注入测试中。

免费 AI IDE


更多建议: