如何在JUnit 5测试中正确使用WireMock响应模板?
问题分析与解决方案
核心问题诊断
你代码里的关键矛盾点在于:
- 你使用的是JUnit 5的注解(
@BeforeEach/@AfterEach),但同时保留了JUnit 4风格的@Rule WireMockRule——JUnit 5完全不识别@Rule注解,所以这个规则里配置的ResponseTemplateTransformer根本没生效。 - 你手动启动的
WireMockServer实例,并没有把ResponseTemplateTransformer加入到它的扩展配置中,只在stub里加了withTransformers("response-template"),这相当于“要求用一个不存在的扩展”,自然无法渲染模板。
修正后的完整代码
下面是适配JUnit 5的正确实现,去掉冗余的WireMockRule,并正确配置模板扩展:
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer; import io.restassured.RestAssured; import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class WireMockTest { private WireMockServer wireMockServer; @BeforeEach public void setup() { // 关键:把ResponseTemplateTransformer加入到WireMockServer的扩展配置中 this.wireMockServer = new WireMockServer( options() .port(8081) .extensions(new ResponseTemplateTransformer(true))); // true表示全局启用模板 this.wireMockServer.stubFor(get(urlEqualTo("/test-url")) .willReturn(aResponse() .withBody("{{request.url}}"))); // 因为全局启用了模板,这里不需要再加withTransformers("response-template") this.wireMockServer.start(); } @Test public void test() { RestAssured.when() .get("http://localhost:8081/test-url") .then() .log().ifError() .body(Matchers.equalTo("/test-url")); } @AfterEach public void tearDown() { if (wireMockServer != null) { wireMockServer.stop(); } } }
关键配置说明
- 全局启用模板:
new ResponseTemplateTransformer(true)中的true参数表示全局启用响应模板,所有stub的响应体都会自动解析模板语法,不需要在每个stub里额外指定withTransformers。 - 非全局启用的方式:如果你只想给特定stub启用模板,可以把构造参数改成
false,然后在stub里加上withTransformers("response-template"),但前提是必须先把扩展加入到server的options中:
// 非全局启用的配置 this.wireMockServer = new WireMockServer( options() .port(8081) .extensions(new ResponseTemplateTransformer(false))); // 特定stub启用模板 this.wireMockServer.stubFor(get(urlEqualTo("/test-url")) .willReturn(aResponse() .withBody("{{request.url}}") .withTransformers("response-template")));
额外注意事项
- JUnit版本一致性:确保你的测试代码里只使用JUnit 5的注解(
org.junit.jupiter.api下的),不要和JUnit 4的org.junit包下的注解混用。 - WireMock版本:建议使用最新稳定版的WireMock(比如3.x以上),旧版本的模板功能可能存在兼容性问题。
- 依赖完整性:确保你的项目依赖中包含了wiremock的响应模板扩展,比如Maven依赖:
<dependency> <groupId>com.github.tomakehurst</groupId> <artifactId>wiremock-jre8</artifactId> <version>3.3.1</version> <scope>test</scope> </dependency>
内容的提问来源于stack exchange,提问作者Kenpachi
相关产品推荐
相关产品推荐

