LoginSignup
1
2

More than 5 years have passed since last update.

Swiftでのプライベートプロパティのテスト方法

Last updated at Posted at 2019-01-12

問題

Swiftでコードを書く場合、Viewのテストで内部のプロパティが正常に設定されているかどうか検証したいが、そのためにプロパティを公開したくない。

解決策

JSON文字列でエクスポートするメソッドを定義して、テストクラス側でJSONに組み立てて検証する。

コード例

JSONパーサーはSwiftyJSONを使っています。

プロダクトコード側

class TableViewCell: UITableViewCell {

    override var debugDescription: String {
        return JSON(["title" : titleLabel.text ?? "", "subtitle" : subTitleLabel.text ?? ""]).debugDescription
    }

}

テストコード側でJSONに組み立てて検証します。

テストコード側

   func test_properties() {

        XCTAssertEqual(JSON(parseJSON:tableViewCell.debugDescription), JSON(["title": "ssss", "subtitle" : ""]))
    }

課題

・チーム開発で、各人のレベル差、意識差まちまちの場合、意図を汲み取れずアクセさーメソッドのような意図しない使われ方をする?
・プロパティ名等をリファクタリングする場合、ビルド時ではなく、テスト実施時にエラーが見つかるため、やや脆いテストになる。

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