Skip to content

Commit

Permalink
feat: register WireMockServer as a Spring Bean (refs #73)
Browse files Browse the repository at this point in the history
  • Loading branch information
tomasbjerre committed Jan 19, 2025
1 parent 53a4378 commit 28df938
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/main/java/org/wiremock/spring/ConfigureWireMock.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.github.tomakehurst.wiremock.extension.ExtensionFactory;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.springframework.beans.factory.annotation.Autowired;

/**
* Configures WireMock instance.
Expand Down Expand Up @@ -125,4 +126,10 @@
* between test runs.
*/
boolean resetWireMockServer() default true;

/**
* If <code>true</code>, it will register {@link WireMockServer} as a Spring Bean so that it can
* be {@link Autowired} by name.
*/
boolean registerSpringBean() default false;
}
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,11 @@ public WireMockServer createWireMockServer(
});
}

if (options.registerSpringBean()) {
this.logger.info("Registering WireMockServer '" + options.name() + "' as a Spring Bean.");
context.getBeanFactory().registerSingleton(options.name(), newServer);
}

return newServer;
}

Expand Down
33 changes: 33 additions & 0 deletions src/test/java/usecases/AutowireNamedWireMockServerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package usecases;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;

import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.wiremock.spring.ConfigureWireMock;
import org.wiremock.spring.EnableWireMock;

@SpringBootTest
@EnableWireMock(@ConfigureWireMock(name = "mywiremock", registerSpringBean = true))
class AutowireNamedWireMockServerTest {

@Qualifier("mywiremock")
@Autowired
private WireMockServer wireMockServer;

@Value("${wiremock.server.baseUrl}")
private String wiremockUrl;

@Test
void returnsTodos() {
this.wireMockServer.stubFor(get("/ping").willReturn(aResponse().withStatus(200)));

RestAssured.when().get(this.wiremockUrl + "/ping").then().statusCode(200);
}
}

0 comments on commit 28df938

Please sign in to comment.