1
2

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 1 year has passed since last update.

SwiftAdvent Calendar 2022

Day 14

【Swift】Stubデータ作成に便利なお手軽protocol紹介

Last updated at Posted at 2022-12-13

定義

public protocol Stubbable {
    static func stub(_ edit: (inout Self) -> Void) -> Self
    static func stub() -> Self
}

public extension Stubbable {
    static func stub(_ edit: (inout Self) -> Void) -> Self {
       var stub = stub()
       edit(&stub)

       return stub
   }
}

使い方

struct User {
    var id: String
    var name: String
    var followers: Int
}

// 別ファイル(テストターゲット内)でextensionしてもOK
extension User: Stubbable {
    // デフォルトのスタブを定義
    static func stub() -> User {
        User(
            id: "1",
            name: "John Smith",
            followers: 10
        )
    }
}

// デフォルトのスタブを生成
let user1: User = .stub()

// デフォルトから任意のパラメーターを変更して生成(テスト時に便利)
let user2: User = .stub { $0.id = "2" } 

補足

ライブラリならもっと素晴らしいものがあります

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?