関数やクラスのtestをやらなきゃなー思って...
とりあえず、やり方だけ覚えとこう(実際やるかはまた別のお話w
プロジェクト作成
TestSample
というプロジェクトを作成します
作成時にこの2つにチェックを入れておきます
(チェックしてなくても後から足すこともできますが今回説明は割愛します。こちらを参考に...)
プロジェクト設定
プロジェクト設定を少し変更します
Defines Module
をYES
にします
MainCode
メインのところにコードを書きます
今回は、簡単に新しいMySample.swift
ファイルを作成して、クラスとaddメソッドを追加します
import Foundation
import UIKit
open class MySample {
public func add(a: Int, b: Int) -> Int {
return a + b
}
}
引数を足すだけの簡単な関数ですw
MySample.swift
の右側のチェックをつけておくことで、Test側でも参照できるようにしておきます
TestCode
先ほど作ったaddメソッドをtestします
最初にチェックしておいたことで[プロジェクト名]Test
フォルダができていると思います
[プロジェクト名]Test.swift
を開くとすでにコードが書いてあります
@testable import [プロジェクト名]
で先ほどメインに書いたクラスを参照できます
import XCTest
@testable import TestSample
class TestSampleTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
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.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
testしたいメソッドの追加
test
から始まるメソッドを追加します
(test
から始めるメソッド名にすることで、testと認識してくれます)
import XCTest
@testable import TestSample
class TestSampleTests: XCTestCase {
// 省略
func testMySample() {
let mySample = MySample()
let add = mySample.add(a: 2, b: 3)
// addメソッドの返り値が5であるかの判断
XCTAssertEqual(add, 5)
}
}
テストの実行
command + U
で実行できます
左から5番目の場所に表示されます
実行して成功したものには、緑のマークがつきます
実行して失敗したものには、赤のマークがつきます
個別実行
testをメソッドごとに個別に実行したい場合、そのメソッドにマウスを合わせると実行マークに変わるので選択すると実行できます
成功と失敗
先ほど書いたコードのXCTAssertEqual
で成功か失敗かを判断します
なので、わざと失敗させてみたいと思います
import XCTest
@testable import TestSample
class TestSampleTests: XCTestCase {
// 省略
func testMySample() {
let mySample = MySample()
let add = mySample.add(a: 2, b: 3)
XCTAssertEqual(add, 4)
}
}
2 + 3
が4
になるとしてみますw
(もちろん失敗しますw)
(XCTAssert
の他のメソッドはこちらを参考に...)