Reputation: 6127
Wire mock has a addMockServiceRequestListener
function available on the JUnit4 Rule or on a wiremock server instance.
How do I get to that function from a test class annotated with JUnit 5's @WireMockTest
annotation?
More generally, how do I get an instance of the WireMockServer
from a test in a class that uses @WireMockTest
?
Upvotes: 5
Views: 7994
Reputation: 4149
There's a better option in newer versions of WireMock than calling addMockServiceRequestListener
, which is to register a PostServeAction
implementation as an extension when configuring JUnit:
@RegisterExtension
static WireMockExtension wm =
WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort()
.extensions(new PostServeAction() {
@Override
public String getName() {
return "my-action";
}
@Override
public void doGlobalAction(ServeEvent serveEvent, Admin admin) {
// Do something
}
}))
.build();
PostServeAction
implementations are the "proper" way to listen for events and will still work in future versions, whereas listeners will be deprecated and removed eventually. They also are given more context about the request than listeners.
Upvotes: 2
Reputation: 8393
Would retrieving the DSL from WireMockRunTimeInfo
sufficient in your case?
https://wiremock.org/docs/junit-jupiter/
From WireMockRunTimeInfo
, there is a getWireMock()
method which returns WireMock.
Example:
@WireMockTest
public class DeclarativeWireMockTest {
@Test
void test_something_with_wiremock(WireMockRuntimeInfo wmRuntimeInfo) {
// The static DSL will be automatically configured for you
stubFor(get("/static-dsl").willReturn(ok()));
// Instance DSL can be obtained from the runtime info parameter
WireMock wireMock = wmRuntimeInfo.getWireMock();
wireMock.register(get("/instance-dsl").willReturn(ok()));
// Info such as port numbers is also available
int port = wmRuntimeInfo.getHttpPort();
// Do some testing...
}
}
Upvotes: 1