我正在尝试使用WireMock的响应模板功能,但它似乎不适用于文档中提供的示例代码。
这是一段示例代码:
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 com.github.tomakehurst.wiremock.junit.WireMockRule;
import io.restassured.RestAssured;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class WireMockTest {
@Rule
public WireMockRule wm = new WireMockRule(options()
.extensions(new ResponseTemplateTransformer(true)));
private WireMockServer wireMockServer;
@BeforeEach
public void setup() {
this.wireMockServer = new WireMockServer(
options().port(8081));
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() {
wireMockServer.stop();
}
}
Run Code Online (Sandbox Code Playgroud)
测试应该通过。(意味着 {{request.url}} 应该被替换/test-url为模板渲染的结果)。
....
java.lang.AssertionError: 1 expectation failed.
Response body doesn't match expectation.
Expected: "/test-url"
Actual: {{request.url}}
Run Code Online (Sandbox Code Playgroud)
@Rule WireMockRule,而是添加了.withTransformers("response-template"). ....
java.lang.AssertionError: 1 expectation failed.
Response body doesn't match expectation.
Expected: "/test-url"
Actual: {{request.url}}
Run Code Online (Sandbox Code Playgroud)
(连同withTransformers)
3. 更改WireMockRule为
@Rule
public WireMockRule wm = new WireMockRule(options()
.extensions(new ResponseTemplateTransformer(false))
);
Run Code Online (Sandbox Code Playgroud)
(连同 withTransformers)
4. 删除了withTransformers唯一保留WireMockRule. (JUnit 4)
5. 我也尝试过上述与 JUnit 5 API 的组合。
但上述变化都没有奏效。有什么我想念的吗?
该@Rule方法将不起作用,因为您WireMockServer在@BeforeEach.
您应该删除的规则,并添加ResponseTemplateTransformer你@BeforeEach到WireMockServer过的Options对象。
像这样的事情应该可以解决问题(从 Javadoc 判断)。
@BeforeEach
public void setup() {
this.wireMockServer = new WireMockServer(
options()
.extensions(new ResponseTemplateTransformer(false))
.port(8081));
this.wireMockServer.stubFor(get(urlEqualTo("/test-url"))
.willReturn(aResponse()
.withBody("{{request.url}}")
.withTransformers("response-template")));
this.wireMockServer.start();
}
Run Code Online (Sandbox Code Playgroud)
您可以编写自己的 Junit Jupiter 扩展。
只是给你举个例子
public class WireMockJunitJupiterExtension implements BeforeAllCallback, AfterAllCallback, ExecutionCondition {
private static final ExtensionContext.Namespace NAMESPACE = create(WireMockJunitJupiterExtension.class);
private static final String WIREMOCK = "wiremock";
@Override
public void afterAll(ExtensionContext context) {
final var server = context.getStore(NAMESPACE).get("wiremock", WireMockServer.class);
server.stop();
server.resetAll();
}
@Override
public void beforeAll(ExtensionContext context) {
final var store = context.getStore(NAMESPACE);
final var server = new WireMockServer(context.getRequiredTestClass().getAnnotation(WireMock.class).port());
findFields(context.getRequiredTestClass(), field -> field.isAnnotationPresent(WithWireMock.class), TOP_DOWN)
.stream()
.map(field -> tryToReadFieldValue(field)
.andThen(o -> call(() -> (MappingBuilder) o))
.getOrThrow(RuntimeException::new)
).forEach(server::stubFor);
store.put(WIREMOCK, server);
server.start();
}
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
final var shouldRun = context.getRequiredTestClass().isAnnotationPresent(WireMock.class);
return shouldRun ? enabled("Started WireMock server") : disabled("Skipped starting WireMock server");
}
}
Run Code Online (Sandbox Code Playgroud)
注释
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(WireMockJunitJupiterExtension.class)
public @interface WireMock {
int port();
}
Run Code Online (Sandbox Code Playgroud)
@Retention(RetentionPolicy.RUNTIME)
public @interface WithWireMock {
}
Run Code Online (Sandbox Code Playgroud)
以及如何使用它
@WireMock(port = 8077)
public class EventsExporterITTest {
@WithWireMock
static MappingBuilder mappingBuilder = post(urlPathEqualTo("path_uri"))
.withRequestBody(equalToJson(readJsonFromFile("file.json")))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json"));
@Test
public void someTest() {
}
}
Run Code Online (Sandbox Code Playgroud)
2021 更新,看起来相当于为 JUnit 5 用户创建了 WireMockRule。
class MyTest {
@RegisterExtension
static WireMockExtension wm = WireMockExtension.newInstance()
.options(wireMockConfig()
.dynamicPort()
.dynamicHttpsPort()
.extension(...))
.build();
@Test
testFoo() {
vm.stubFor(...);
doSomethingUsingUrl(vm.getRuntimeInfo.getHttpBaseUrl() + "/test")
vm.verify(...);
}
}
Run Code Online (Sandbox Code Playgroud)
(wm.getRuntimeInfo().getHttpBaseUrl()包括wm.getRuntimeInfo().getHttpPort()- 耶)
请参阅Advanced usage - programmatic此处的部分:
http://wiremock.org/docs/junit-jupiter/