LoginSignup
43
42

More than 3 years have passed since last update.

Swift向け単体テスト(Unit Test)の作り方

Posted at

はじめに

Mac環境の記事ですが、Windows環境も同じ手順になります。環境依存の部分は読み替えてお試しください。

目的

この記事を最後まで読むと、次のことができるようになります。

  • テスト環境を準備する
  • 単体テスト(Unit Test)を作成する

テストターケッド

ViewController.swift
import UIKit

class ViewController: UIViewController {

    var subClass: SubClass!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.subClass = SubClass(viewController: self)
    }

    class SubClass {
        private let viewController: ViewController

        init(viewController: ViewController) {
            self.viewController = viewController
        }

        func multiply(num1: Int, num2: Int) -> Int {
            return num1 * num2
        }
    }

}

テストコード

swift_UnitTestTests.swift
import XCTest
@testable import swift_UnitTest

class swift_UnitTestTests: XCTestCase {

    var viewController: ViewController!

    override func setUp() {
        // Put setup code here. This method is called before the invocation of each test method in the class.
        super.setUp()
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        self.viewController = storyboard.instantiateInitialViewController() as? ViewController
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
        viewController.loadViewIfNeeded()
        let subClass = viewController.subClass
        let result = subClass?.multiply(num1: 7, num2: 28)
        XCTAssertEqual(result, 196)
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }

}

テスト結果

スクリーンショット 2019-08-23 16.29.24.png

関連する記事

実行環境

環境 Ver.
macOS Mojave 10.14.6
Xcode 10.3

ソースコード

実際に実装内容やソースコードを追いながら読むとより理解が深まるかと思います。是非ご活用ください。

GitHub

テストシナリオ

  1. ViewControllerにかけ算の結果を返すメソッドを作成する

  2. かけ算の結果が正常であるか単体テストにて確認する

かけ算メソッドの実装

ViewController.swift
import UIKit

class ViewController: UIViewController {

    var subClass: SubClass!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.subClass = SubClass(viewController: self)
    }

    class SubClass {
        private let viewController: ViewController

        init(viewController: ViewController) {
            self.viewController = viewController
        }

        func multiply(num1: Int, num2: Int) -> Int {
            return num1 * num2
        }
    }

}

テスト環境の準備

ファイル構成はこのようになります。

スクリーンショット 2019-08-23 10.00.24.png

Unit Testsを事前に準備する場合

プロジェクトの作成時にInclude Unit Testsにチェックを入れて作成する

スクリーンショット 2019-08-23 9.57.15.png

Unit Testsを後から準備する場合

File > New > Target...をクリックする

Testセクションの中のiOS Unit Testing Bundleを選択してNextをクリッックする

スクリーンショット 2019-08-23 17.20.49.png

情報を入力してFinishをクリッックする

スクリーンショット 2019-08-23 17.24.19.png

テストケースの作成

swift_UnitTestTests.swift
import XCTest
@testable import swift_UnitTest

class swift_UnitTestTests: XCTestCase {

    var viewController: ViewController!

    override func setUp() {
        // Put setup code here. This method is called before the invocation of each test method in the class.
        super.setUp()
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        self.viewController = storyboard.instantiateInitialViewController() as? ViewController
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
        viewController.loadViewIfNeeded()
        let subClass = viewController.subClass
        let result = subClass?.multiply(num1: 7, num2: 28)
        XCTAssertEqual(result, 196)
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }

}

テストの実施

単体でテストを実施する場合

行番号上の再生ボタンをクリックする

スクリーンショット 2019-08-23 17.40.01.png

全体でテストを実施する場合

Product > Testをクリックする

気をつけるポイント

CocoaPodsでパッケージをインストールしている場合は、テスト環境でパッケージが読み込めずエラーとなる

PodfileのTargetにテスト環境を追加して更新する

例) パッケージ(Kanna)をインストールした場合

Podfile.rb
# Uncomment the next line to define a global platform for your project
platform :ios, '12.0'

target 'swift_UnitTest' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!
  # Pods for swift_UnitTest
  pod 'Kanna', '4.0.3'
end

target 'swift_UnitTestTests' do
  inherit! :search_paths
  # Pods for testing
  pod 'Kanna', '4.0.3'
end
Command.sh
pod update
43
42
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
43
42