WireMockのStandalone版をSpring Bootで動かす
layers Dev/Java
label
Java
label
Spring Boot
label
WireMock
date_range
更新日時 : 2021/01/03 11:49 date_range
投稿日時 : 2021/01/03 11:47概要
- JUnit実行時ではなく、ステージング環境でMock Serverを立てる場合、WireMockのStandaloneで動かすと良さそうだったので、Spring Bootを使って動かしてみた。(jar直接動かせばいいじゃんというツッコミはNG)
サンプルリポジトリ
https://github.com/vagivagi/demo-wiremock-standalone
依存関係
- jre8とあるけど、Java11で動いた。
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8</artifactId>
<version>2.27.2</version>
</dependency>
WireMockServerを動かす
- 公式ドキュメントを読むと、
WireMockServer
クラスのインスタンスを作成して、起動する必要がある。
- まずはBean定義する
@Bean
WireMockServer wireMockServer(@Value("${server.port}") int port) {
WireMockConfiguration configuration = WireMockConfiguration
.wireMockConfig()
.port(port)
.usingFilesUnderDirectory("src/main/resources/mock");
return new WireMockServer(configuration);
}
spring.main.web-application-type
をnone
に設定する
- Standaloneで動かすと、Jettyが起動するが、Spring BootでWebをデフォルトで動かすと、Tomcatがポート8080で動くため、Tomcatを起動しないように設定変更する。両方動かしたい場合はどちらかのポート番号変更する。
server.port=8080
spring.main.web-application-type=none
- 起動時に
WireMockServer.start
を実行する
- 1の手順でBean定義したが、このままだと起動しないので、Bean作成後にメソッド実行する必要がある。
@PostConstruct
アノテーションでもできそうだが、今回はInitiaizingBean
インターフェイスを実装する形にした。- 念の為、
@PreDestroy
でstopメソッド実行するようにしたが、あまり意味はないかも。(プロセス終了時にどちらにしろ停止するので...)
@Component
public class WireMockServerInit implements InitializingBean {
private final WireMockServer wireMockServer;
public WireMockServerInit(WireMockServer wireMockServer) {
this.wireMockServer = wireMockServer;
}
@Override
public void afterPropertiesSet() throws Exception {
wireMockServer.start();
}
@PreDestroy
public void onExit() {
wireMockServer.stop();
}
}
src/main/resouces/mock
にマッピングファイル(JSON)を置く
- 順番が前後するが、デフォルトの
src/test/resources
ディレクトリから配置を変更しているので、1で定義したディレクトリにWireMockのマッピングファイルを置く
- Spring Bootを起動して、管理者用のAPIを実行して、マッピングが設定されているか確認する
- 管理者用APIのドキュメントを参考に動作確認したところ、2つのファイルがマッピングされていることを確認した。
$ curl -X GET -H "Content-Type: application/json" http://localhost:8080/__admin/mappings
{
"mappings" : [ {
"id" : "ab82ec8d-560a-4a47-9a87-a4b1c3c621fd",
"request" : {
"url" : "/api/test2",
"method" : "GET"
},
"response" : {
"status" : 200,
"body" : "Json test body2"
},
"uuid" : "ab82ec8d-560a-4a47-9a87-a4b1c3c621fd"
}, {
"id" : "acd87861-c71f-4d23-bcae-c5359f29030b",
"request" : {
"url" : "/api/test",
"method" : "GET"
},
"response" : {
"status" : 200,
"body" : "Json test body"
},
"uuid" : "acd87861-c71f-4d23-bcae-c5359f29030b"
} ],
"meta" : {
"total" : 2
}
}
今後
設定と起動はうまくできた。今後は、TomcatとJettyを同時に動かす場合のコンテナ化やマッピングファイルのディレクトリを動的に動かすことを試してみたい。