Help us understand the problem. What is going on with this article?

テスト用の画像をネットワークから読み出さないようにする。

More than 1 year has passed since last update.

はじめに

組織にテストを書く文化を根付かせる戦略と戦術にある通り、ユニットテストは最低限、再現性と繰り返し性を追求する必要があります。

サーバー(=ネットワーク)につなぐ処理はそれを阻害する要因なので、スタブやモックを使って断ち切る必要があります。

Rest APIをスタブする方法が色々出回っているのでここで述べません。

一方、テスト画像をスタブするにはどうすれば良いでしょうか? わざわざスタブを書く? いえ、画像キャッシュライブラリの機能を使えば書かなくて済みます!

実際のコード例

実際のコードはこんな感じになります。SDWebImage限定です。XCTestCaseクラスのSetUpメソッド辺りで呼びましょう。

   let cache = SDImageCache.shared()
        cache?.maxCacheSize = 50 * 1024 * 1024
        for name in ["item_1", "item_2", "item_3", "item_4", "item_5", "item_6"] {
            let url = Bundle(for: type(of: self)).url(forResource: name, withExtension: "png")
            let data = try! Data(contentsOf:url!)
            cache?.removeImage(forKey:  "https://hogehoge.com/" + name)
            cache?.store(UIImage(data: data), forKey:  "https://hogehoge.com/" + name)
        }

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away