Swift TDD

Swift TDD

  • 아래의 글은 Swift의 Unit Test를 Xcode에서 진행하는 방법을 설명한다.

우선 프로젝트를 Single View App으로 선택한 후 Product Name을 작성한다.

TDD

include Unit Tests: Unit Test를 Project 생성시 생성할 것인지 체크하는 부분이다.
include UI Tests: UI Test를 Project 생성시 생성할 것인지 체크하는 부분이다.

Next를 눌러서 원하는 곳에 프로젝트를 생성해준다.

TDD

Command + 6을 누르거나 Show the Test navigator를 선택해준다.

초기에 Project생성시에 include Unit Tests, include UI Tests 를 체크하였기 때문에 생성되어 있는것이다.

만약 초기에 선택을 못하였거나 Test를 추가하고 싶다면 아래의 + 버튼을 누르면 된다.

TDD

Unit Test를 하기위해서 FiboTddPraticeTests를 선택하면 아래와 같은 코드가 나타난다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import XCTest
// 어떤 프로젝트를 Test할것인지 import해줘야한다.
@testable import FiboTddPratice

class FiboTddPraticeTests: 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.
}
}

}

위의 SetUp() Method, tearDown() Method에 대하여 알아보자.

SetUP()

SetUp() Method는 각 Test Case의 Test Method가 불리기 전에 상태를 reset할 기회를 제공한다.

SetUp Instance Method는 각 테스트가 시작되기 전에 한 번 호출된다.

SetUp Method를 Override하여서 각 Test Method의 상태를 다시 설정한다.

SetUp Method Link

tearDown()

tearDown() Method는 Test Case의 Test Method가 끝난 후에 Clean Up을 할 기회를 제공한다.

tearDown Instance Method는 각 테스트가 완료된 후에 한 번 호출된다. test 마다 clean up을 수행하려면 Override하라.

tearDown Method Link

TDD 시작

우선 FiboTddPraticeTests Class안에 만들고 싶은 Class의 property를 생성해준다.
그러면 당연히 Error가 날 것이다. 왜냐하면 생성을 해주지 않았기 때문이다.

TDD

여기서 먼저 Error가 나는 것을 확인한 후에 Class를 생성해줘야한다.

1
2
3
4
5
6
import Foundation

class Fibonacci {

}

Project에 Fibonacci.swift 파일을 생성하고 Class만 생성해준다.

그러면 Error(Red)가 사라질 것이다.

Share