// src/test/java/.../support/WireMockStubs.java
package com.example.test.support;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import java.util.List;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
public final class WireMockStubs {
private WireMockStubs() {}
/** GET 固定 JSON */
public static void stubGetJson(WireMockExtension wm, String url, String json) {
wm.stubFor(get(urlEqualTo(url)).willReturn(okJson(json)));
}
/** POST 固定 JSON(status 任意) */
public static void stubPostJson(WireMockExtension wm, String url, String json, int status) {
wm.stubFor(post(urlEqualTo(url))
.willReturn(aResponse().withStatus(status)
.withHeader("Content-Type", "application/json")
.withBody(json)));
}
/** GET 動的(Handlebars:{{request.query.xxx}} 可) */
public static void stubGetDynamic(WireMockExtension wm, String urlPath, String bodyTemplate) {
wm.stubFor(get(urlPathEqualTo(urlPath))
.willReturn(aResponse().withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(bodyTemplate)));
}
/** POST 動的(JSONPath:{{jsonPath request.body '$.id'}} 可) */
public static void stubPostDynamic(WireMockExtension wm, String url, String bodyTemplate) {
wm.stubFor(post(urlEqualTo(url))
.willReturn(aResponse().withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(bodyTemplate)));
}
/** 同一エンドポイントで逐次応答(GET/POST 両対応) */
public static void stubSequential(
WireMockExtension wm, String method, String url, List<String> bodies, int status, String contentType) {
final String scenario = method.toUpperCase() + " " + url + " SEQ";
String state = "STARTED";
for (int i = 0; i < bodies.size(); i++) {
String next = (i == bodies.size() - 1) ? "DONE" : "CALL_" + (i + 1);
var mapping = method.equalsIgnoreCase("GET") ? get(urlEqualTo(url)) : post(urlEqualTo(url));
wm.stubFor(mapping
.inScenario(scenario).whenScenarioStateIs(state)
.willReturn(aResponse().withStatus(status)
.withHeader("Content-Type", contentType)
.withBody(bodies.get(i)))
.willSetStateTo(next));
state = next;
}
var mapping = method.equalsIgnoreCase("GET") ? get(urlEqualTo(url)) : post(urlEqualTo(url));
wm.stubFor(mapping.inScenario(scenario).whenScenarioStateIs("DONE")
.willReturn(aResponse().withStatus(status)
.withHeader("Content-Type", contentType)
.withBody(bodies.getLast())));
}
}
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme