LoginSignup
0
0

More than 3 years have passed since last update.

Quickの非同期処理テストではactualを展開しない

Last updated at Posted at 2019-09-20

tl;dr

swiftでQuick/Nimble/BrightFuturesを使った非同期処理のテストを書いていた時にハマったののメモ

事象

バックエンドにRESTを投げた後、レスポンスの内容を確認するテストで下記エラーが出た。
複数のエレメントを持つJSONを取得する想定だったので、配列化された要素の中身を検証しようとしていた。

エラー内容

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
2019-09-20 09:32:20.858612+0900 xxxxxxx[25589:7494225] Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

テストコード


it ("何かの情報を取得できる") {
               var actualPromise: [SomeSturct]!
               subject.getSomeSturct()
                   .onSuccess { success in
                       actualPromise = success
                   }
               let someSturctResponse =
                                   """
                                       [
                                           {
                                           "Key": "Value"
                                           }
                                       ]
                                   """
               expectedPromise.success(someSturctResponse.data(using: .utf8)!)

               expect(actualPromise[0].key).toEventually(equal("Value"))
           }


原因

nilのエラーなので、何かのオブジェクトがnilのはず。
非同期処理のテストなのでtoEventuallyを使っていたが、toEventuallyは成功するまでアサーションを繰り返し続けるので、
まだ値が取得できていないタイミングでactualを展開するような処理をするとnilで落ちてしまう。

なので展開せずにテストするような形で修正することで対応する。
テスト的にもこっちが正しい気がする。


// expect(actualPromise[0].key).toEventually(equal("Value")) →
expect(actualPromise).toEventually(equal([SomeSturct(Key: "Value")]))

参考

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