覚えたら書く

IT関係のデベロッパとして日々覚えたことを書き残したいです。twitter: @yyoshikaw

はじめてのstubby4j

テストをしている際などに、自分の好きなようにレスポンスを返してくれるHTTPサーバがほしくなる場合があります。
そういう時は、stubby4jを利用すると任意のHTTPレスポンスを返すためのモックサーバを簡単に立てられます。
返すレスポンスの内容はYAMLファイルで指定します。


以下のコマンドで実行(サーバを起動)できます。非常に簡単

java -jar stubby4j-x.x.xx.jar -d {YAMLファイルのパス}
  • レスポンスを定義するYAMLの例
# JSON形式でデータを応答
-  request:
      method: [GET]
      url: /SampleServer/parameter

   response:
      -  status: 200
         headers:
            content-type: application/json; charset=UTF-8
         file: ../json/Params.json


# XML形式でデータを応答
-  request:
      method: [GET]
      url: /SampleServer/hello.xml

   response:
      -  status: 200
         headers:
            content-type: application/xml; charset=UTF-8
         file: ../xml/hello.xml


# バイナリデータを応答
-  request:
      method: [GET]
      url: /SampleServer/Application.exe

   response:
      -  status: 200
         headers:
            content-type: application/octet-stream
         file: ../exe/Application.exe


サンプル

ディレクトリ構成を以下のようにする(Sample.ymlには上記例のYAMLの内容が書かれているとします)

/
│
├─json
│      Params.json
│
├─xml
│      hello.xml
│
├─server
│      Sample.yml
│      stubby4j-3.3.0.jar
│
└─exe
      Application.exe

サーバ起動(上記ディレクトリのserverディレクトリ内で以下コマンドを実行)

java -jar stubby4j-3.3.0.jar -d Sample.yml

サーバが起動する(コンソールに以下のような表示がされる)

C:\Stubby\server>java -jar stubby4j-3.3.0.jar -d Sample.yml
Loaded: [GET] /SampleServer/parameter
Loaded: [GET] /SampleServer/hello.xml
Loaded: [GET] /SampleServer/Application.exe

Admin portal configured at http://localhost:8889
Admin portal status enabled at http://localhost:8889/status
Stubs portal configured at http://localhost:8882
Stubs portal configured with TLS at https://localhost:7443 using internal keystore
Jetty successfully started

Quit: ctrl-c


サーバのステータスを確認する場合は以下にアクセス

http://localhost:8889/status

こんな画面が出ます f:id:nini_y:20160907214220p:plain


YAMLで定義した各URLにアクセスする場合は以下の通り

  • http://localhost:8882/SampleServer/parameter
  • http://localhost:8882/SampleServer/hello.xml
  • http://localhost:8882/SampleServer/Application.exe


http://localhost:8882/SampleServer/parameter にアクセスした場合(JSONが返ってくるURL)、以下の通り

f:id:nini_y:20160907214226p:plain


アクセスがあるたびに以下のような内容がコンソールに出力される

[21:38:31] -> GET [/SampleServer/parameter]
[21:38:31] <- 200 [/SampleServer/parameter] OK
[21:39:04] -> GET [/SampleServer/hello.xml]
[21:39:04] <- 200 [/SampleServer/hello.xml] OK


本記事では、かなり単純な例しか書いていませんが、stubby4jではもっと複雑なこともできます。(以下記事参照)