Gonen I
Gonen I

Reputation: 6127

How to get to a WireMockServer from Junit 5 WireMockTest test case

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

Answers (2)

Tom
Tom

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

jcompetence
jcompetence

Reputation: 8393

Would retrieving the DSL from WireMockRunTimeInfo sufficient in your case?

https://wiremock.org/docs/junit-jupiter/

https://javadoc.io/doc/com.github.tomakehurst/wiremock-jre8/latest/com/github/tomakehurst/wiremock/junit5/WireMockRuntimeInfo.html#getWireMock--

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

Related Questions