LoginSignup
3
2

More than 3 years have passed since last update.

PostmanでAPIのレスポンスが正しいかテストする

Posted at

Postman

Postman | The Collaboration Platform for API Development

そもそもPostmanとは?

APIの動作を確認するツール、、だけに留まらず今や認証、テスト、ドキュメント作成、バージョン管理など幅広く活用できる便利なツール&サービスです。:sparkles:

Postmanでテストする

Test examples | Postman Learning Center

Postmanではレスポンスの値をテストする事ができます。
Postmanを開いて Params, Authorization... などがあるタブの左端に Tests というタブがあるので
そちらにテストを書く事ができます。
2.png

試しに簡単なテストを書いてみる

試しに、GithubAPIを使ってリポジトリのブランチ一覧を取得してみます。
GitHub API v3 | GitHub Developer Guide

今回はrails/railsのブランチ一覧を取得するAPIをPostmanでリクエストしてみます。

https://api.github.com/repos/rails/rails/branches

↑をPostmanに設定し「Send」を押すとズラズラっとブランチが取得できるかと思います :ok_hand:
3.png

レスポンスとしては以下の様なフォーマットで返って来ます。(※ 2019年9月16日時点)

[
    {
        "name": "1-2-stable",
        "commit": {
            "sha": "5b3f7563ae1b4a7160fda7fe34240d40c5777dcd",
            "url": "https://api.github.com/repos/rails/rails/commits/5b3f7563ae1b4a7160fda7fe34240d40c5777dcd"
        },
        "protected": true
    },
    {
        "name": "2-0-stable",
        "commit": {
            "sha": "81d828a14c82b882e31612431a56f830bdc1076f",
            "url": "https://api.github.com/repos/rails/rails/commits/81d828a14c82b882e31612431a56f830bdc1076f"
        },
        "protected": true
    },
    ...
]

今回はテストとして
・ ステータス200でレスポンスが返ってくる事
・ ↑のjson schemaで返ってくる事
のテストを書いてみます。 :heavy_check_mark:

ステータス200でレスポンスが返ってくる事

こちらは簡単で以下の様に記述します。

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

↑を「Tests」タブ内に書いて、「Send」を押すと下の「Test Results」に
テスト結果が表示されます。
4.png

失敗すると赤くなって、失敗理由が表示されます。
5.png

json schemaのチェック

Postmanではjosn schemaのチェックに「tv4」と「ajv」が使用できます。

今回は、「tv4」を使ってチェックを行いたいと思います。

let schema = {
    "title": "branches",
    "type": "array",
    "properties": {
        "name": {
            "type": "string"
        },
        "commit": {
            "type": "object",
            "properties": {
                "sha": {
                    "type": "string"
                },
                "url": {
                    "type": "string"
                }
            }
        },
        "protected": {
            "type": "boolean"
        }
    }
};

pm.test("Body matches", function () {
    var jsonData = pm.response.json();
    pm.expect(tv4.validate(jsonData, scheme)).to.be.true;
});

↑やっている事はレスポンスのjson schemaを事前に定義して let schema
実際のレスポンスと合っているかチェックしています。
※ 定義に関しての詳細はこちらを参照

「Tests」に追記し、「Send」を実行しテスト結果がグリーンであれば成功です :sparkles:

参考URL

3
2
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
3
2