0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Swiftでのユニットテストの使い方 初心者向け

Posted at

Swiftアプリ開発では、バグを防ぎ、安心してリファクタリングするためにユニットテストが欠かせません。この記事では、XCTestを使ったSwiftの基本的なテストの書き方と実行方法を紹介します。

テストの準備

テストターゲットを追加する
Xcodeで
File → New → Target... → iOS Unit Testing Bundle
を選ぶと、プロジェクト名Testsというターゲットが作られます。

テストケースを書く

import XCTest
@testable import プロジェクト名

final class SampleTests: XCTestCase {
    
    func testAddition() {
        let result = 2 + 3
        XCTAssertEqual(result, 5)
    }
    
    func testIsEven() {
        let number = 4
        XCTAssertTrue(number % 2 == 0)
    }
}

よく使うアサーション

メソッド 概要
XCTAssertEqual(a, b) a と b が等しいこと
XCTAssertTrue(condition) 条件が true であること
XCTAssertNil(value) 値が nil であること
XCTAssertNotNil(value) 値が nil でないこと
XCTFail() 無条件で失敗

SwiftUIでも使える?

ユニットテストは主にロジック部分に使うのが基本です!
SwiftUIのViewはUIテストという別の所で確認します。
しかし、ViewModelのテストはこの方法で大丈夫です!

まとめ

  • XcodeのXCTestを使う

  • ビジネスロジックはユニットテストで試す!

  • Viewの動作確認はUIテストへ

以上がSwiftでのユニットテストの使い方の説明でした!ぜひ参考にしてみてください!!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?