LoginSignup
7
9

More than 5 years have passed since last update.

Quick + Nimble で APIKit の非同期テストを書く

Posted at

API をモックして非同期テスト書こうとしたらちょっとハマったのでメモ。
APIKit の使い方とか Quick, Nimble の書き方はググってください。

Versions

  • Xcode 7.3.1
  • Swift 2.2
  • Quick 0.9.2
  • Nimble 4.1.0
  • OHHTTPStubs 5.1.0
  • APIKit 2.0.3

コード

import Quick
import Nimble
import APIKit
import OHHTTPStubs
@testable import your_project

class LoginRequestSpec: QuickSpec {
  override func spec() {
    describe("LoginRequest") {
      beforeEach {
        stub(isHost("example.com")) { _ in
          // 想定されるレスポンスの json を同階層に設置する
          let stubPath = OHPathForFile("OK.json", self.dynamicType)
          return fixture(stubPath!, headers: ["Content-Type": "application/json"])
        }
      }
      afterEach {
        OHHTTPStubs.removeAllStubs()
      }

      context("when Login OK") {
        it("return OK") {
          let request = LoginRequest(authId: "id", password: "pw")
          var okResult = ""
          waitUntil { done in
            Session.sendRequest(request) { result in
              switch result {
              case .Success(let loginResul):
                okResult = loginResult
              case .Failure(_):
                break
              }
              expect(okResult).to(equal("OK"))
              done()
            }
          }
        }
      }
    }
  }
}

ポイント

  1. OHHTTPStubs で Response をモックする。
  2. Session.sendRequestwaitUntil で囲む。
    • 最初 toEventually を使ってたらうまくいかずハマった...
  3. テストが完了したら done() を呼ぶ。

これでテストが通るはず!

7
9
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
7
9