Spring Cloud 替代:使用JUnit规则
2024-01-02 16:47 更新
要获得更常规的WireMock体验,可以使用JUnit @Rules
启动和停止服务器。为此,请使用方便类WireMockSpring
获得一个Options
实例,如以下示例所示:
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class WiremockForDocsClassRuleTests { // Start WireMock on some dynamic port // for some reason `dynamicPort()` is not working properly @ClassRule public static WireMockClassRule wiremock = new WireMockClassRule( WireMockSpring.options().dynamicPort()); // A service that calls out over HTTP to wiremock's port @Autowired private Service service; @Before public void setup() { this.service.setBase("http://localhost:" + wiremock.port()); } // Using the WireMock APIs in the normal way: @Test public void contextLoads() throws Exception { // Stubbing WireMock 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!"); } }
@ClassRule
表示在运行了此类中的所有方法之后,服务器将关闭。
以上内容是否对您有帮助:
更多建议: