29
33

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.

iOSアプリ向け通信スタブの使い方

Last updated at Posted at 2017-01-10

iOSアプリ向けの通信スタブに関する、簡単なまとめです。

Stubライブラリ

  • OHHTTPStubs
    • アプリtargetでも使える。APIKitなどで使用されている。
  • Mockingjay
    • テスト用targetのみ(?)。アプリtargetでは使えない(?)
    • (詳しくは調べていないのですが、XCTestと統合されている、との記述がありました)
  • Moya
    • 通信ライブラリ+ スタブ
    • 1回試したが、APIKitの方が好みでした。

OHHTTPStubsの使い方

https://github.com/AliSoftware/OHHTTPStubs/wiki/Usage-Examples
ここにいろいろあります。

(以下は全てUsage-Examplesより引用)

jsonを返す

stub(isHost("mywebservice.com")) { _ in
  let obj = ["key1":"value1", "key2":["value2A","value2B"]]
  return OHHTTPStubsResponse(JSONObject: obj, statusCode: 200, headers: nil)
}

isHost, isPath, isMethodPOST などを使って条件を設定する

レスポンス時間を変える

stub(isHost("mywebservice.com")) { _ in
  return OHHTTPStubsResponse(JSONObject:someDict, statusCode:200, headers:nil)
    .requestTime(1.0, responseTime: 3.0)
}

エラーを返す

statusCode をエラーコードにする

使用するメリット

  • サーバー実装を待たなくていい
    • 仕様だけあれば開発が進められる。
  • テストコードが書きやすい
    • 実際のAPIだと、認証処理などが必要な場合が多く、テストコードを書くのが難しい。
  • エラー条件のテストができる
    • API毎に設定可能。
  • レスポンス時間を調整できる
    • API毎に設定可能。

開発がどう変わったか?

開発の順番が変わり、モデルレイヤーからボトムアップ的に作れるようになりました。
(それまでは、画面を作る→対応するAPIを作る→実際にアプリを動かして確認 という感じだった)

今の開発フロー

stubを作る

entityを作る

Request(APIKit)を作る

テストを書く ※ 画面を作らなくても動作確認できる!

29
33
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
29
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?