是否可以更改在运行时注册的WireMockExtension端口?
@ExtendWith(SpringExtension.class)
public class BaseIntegrationTest {
...
@RegisterExtension
protected WireMockExtension wm = WireMockExtension.newInstance().options(
wireMockConfig().port(12345).extensions(NoKeepAliveTransformer.class)).build();
public void changePort() {
// wm change port to 123
}
}
任何不使用@RegisterExtension
但仍具有用于存根的wm
变量的相等解决方案都是可以的。
WireMockExtension
只是管理WireMock
服务器实例生命周期的JUnit扩展。若要在运行时更改端口,则需要停止并启动服务器。
看看WireMockExtension的实现,不确定它是为这个用例设计的。我建议在不扩展的情况下管理WireMock
生命周期。
private WireMockServer wireMockServer;
private int wireMockPort = 1000;
@BeforeEach
void startWireMock() {
wireMockServer = new WireMockServer(wireMockConfig().port(wireMockPort));
wireMockServer.start();
WireMock.configureFor(wireMockServer.port());
}
@AfterEach
void stopWireMock() {
wireMockServer.stop();
}
void changePort(int port) {
wireMockPort = port;
}
它将允许您在每次测试前更改端口。如果你需要更精细的控制并在测试过程中更改它,你就不能像那样做任何事情
void changePort(int port) {
stopWireMock();
wireMockPort = port;
startWireMock();
}