1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WireMockでスタブサーバーを立ち上げる

Posted at

WireMockのスタブサーバーとは、HTTP通信が発生するAPIにおいて、送信先のポートをモック化し、期待する返却値を返すようにするものです。

  • 環境
    • Java1.8
    • SpringBoot2系
    • WireMock 2系

1個たてる場合


@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 正常系() {
    stubFor(get(urlEqualTo("/hoge"))
      .willReturn(aResponse()
        .withStatus(200)
        .withBodyFile("hoge.json")))

    //テスト内容...

  }
}
hoge.json
{
  "text": "hogehoge"
}

簡単に解説すると、/hogeにアクセスしたときに200ステータスとhogehogeを返却するスタブサーバーが8081番ポートで立ち上がります。
注意点としてはhoge.jsonを配置する場所です。
src/functionalTest/resources/__files/hoge.json
です。この__filesをわすれて一時間ハマりました。

複数個たてる場合

先にコードを載せておきます。


@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 正常系() {

    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())
    );

    //テスト内容...

  }
}

なんとなくわかると思いますが、/fugaにpostでfugafugaを送ると200番ステータスのみを返却するスタブが追加できました。
利点としては各ルールに対してverifyなどが用意されているので、どのスタブのどんなPOSTリクエストが何回呼ばれたかなどをテストすることができます。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?