WireMock's stub server is an API that causes HTTP communication to mock the destination port and return the expected return value.
--Environment - Java1.8 --Spring Boot 2 series --WireMock 2 series
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class FunctionalTest {
@ClassRule
public static WireMockRule wireMockRule =
new WireMockRule(wireMockConfig().port(8081)
.usingFilesUnderDirectory("src/functionalTest/resources/"));
@Test
public void normal system() {
stubFor(get(urlEqualTo("/hoge"))
.willReturn(aResponse()
.withStatus(200)
.withBodyFile("hoge.json")))
//Test content...
}
}
hoge.json
{
"text": "hogehoge"
}
Briefly, a stub server that returns 200 status and hogehoge when accessing / hoge will start up on port 8081.
Note the location where hoge.json is placed.
src/functionalTest/resources/__files/hoge.json
is. I forgot this __files and got hooked for an hour.
I will put the code first.
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class FunctionalTest {
@Rule
public WireMockRule wireMockRuleHoge =
new WireMockRule(wireMockConfig().port(8081)
.usingFilesUnderDirectory("src/functionalTest/resources/"));
@Rule
public WireMockRule wireMockRuleFuga =
new WireMockRule(wireMockConfig().port(8082)
.usingFilesUnderDirectory("src/functionalTest/resources/"));
@Test
public void normal system() {
wireMockRuleHoge.stubFor(get(urlEqualTo("/hoge"))
.willReturn(aResponse()
.withStatus(200)
.withBodyFile("hoge.json")
)
);
Resource requestResource = resourceLoader.getResource(ResourceLoader.CLASSPATH_URL_PREFIX + "/fuga.json");
String request = FileUtils.readFileToString(requestResourcePerformance.getFile(), UTF_8);
wireMockRuleFuga.stubFor(post(urlEqualTo("/fuga"))
.withRequestBody(equalToJson())
.willReturn(ok())
);
//Test content...
}
}
As you can see, if you send fugafuga to / fuga by post, you can add a stub that returns only the 200th status. As an advantage, verify etc. are prepared for each rule, so you can test what POST request of which stub was called and how many times.
Recommended Posts