XCTest는 실패가 없는한 통과로 간주한다. 따라서, asserts가 없다면(아무것도 테스트하지 않았어도), test는 성공으로 마크된당
모든 XCTAssert는 description을 쓸 수 있다. 테스트 실패시 실패처리에 함께 나온다.
XCTAssertTrue, XCTAssertFalse
func testModel_whenStarted_goalIsNotReached() {
XCTAssertFalse(sut.goalReached, "goalReached should be false when the model is created")
}
func testModel_whenStopsReachGoal_goalIsReached() {
// given
sut.goal = 1000
// when
sut.steps = 1000
// then
XCTAssertTrue(sut.goalReached)
}
Testing Errors
XCTAssertThrowsError, XCTAssertNoThrow
메소드에 throws 키워드를 붙인 후, 마찬가지로 위 테스트 메소드를 사용한다.
View controller testing
ViewController를 테스팅하기 위해서는 view와 conrol을 테스트하는 것이 아닌, viewcontroller의 상태와 로직을 검토하는 목적이다.
기능 테스트는 UI와 로직 메소드를 분리하는 것이 핵심이다.
ViewModel을 controller으로부터 분리하는 것이 로직을 unit-testable하게 만들 수 있다. (Like, VIPER, MVVM)
viewcontroller에서 테스트하는 것들
Action에 의한 로직(State) 변경 로직 테스트
이 때, Action은 View가 처음 로드되었을 때도 해당 (초기 State를 잘 가지고 있는 지 테스트)
viewcontroller를 호출하는 방법
앱이 실행될때, viewcontroller의 view를 호출하면 이미 view가 로드되었기 때문에, view를 이용한 코드되어도 문제가 없다.
하지만 테스트를 할 경우, viewcontroller의 view를 load해주어야한다. (viewcontroller의 생명주기를 테스트할 때는 수동으로 만들어주어야함)
3가지 방법이 있다.
Host App 사용하기
viewDidLoad 호출하기 (viewcontroller 초기화함수에 UI 초기화하기)
스토리보드를 통해 가져오기
Host App 사용하기
Allow testing Host Application APIs 를 체크하면 테스트 작업을 실행할 때, 시뮬레이터나 디바이스에서 호스트앱이 실행된다.
테스트를 시작하기 전에 앱이 로드될 때까지 대기하며, 테스트는 앱의 컨텍스트에서 실행된다.
따라서, 테스트에서 UIApplication 객체와 전체 View 계층에 접근할 수 있게 된다.
// ViewControllers.swift
import UIKit
@testable import FitNess
func getRootViewController() -> RootViewController {
guard let controller =
(UIApplication.shared.connectedScenes.first as? UIWindowScene)?
.windows
.first?
.rootViewController as? RootViewController else {
assert(false, "Did not a get RootViewController")
}
return controller
}
app의 window에서 rootViewController를 얻는다.
rootViewController를 통해 다른 viewcontrollers도 얻기 위한 목적이다.
TDD - Test Expresions
레이먼드 아저씨 책 - iOS Test-Driven Development by Tutorials 의 네번째 챕터 Test Expressions에서 배운 내용
배운 내용
XCTAssert
종류
XCTAssertEqual
XCTAssertNotEqual
XCTAssertTrue
XCTAssertFalse
XCTAssertNil
XCTAssertNotNil
XCTAssertLessThan
,XCTAssertGreaterThan
,XCTAssertLessThanOrEqual
,XCTAssertGreaterThanOrEqual
XCTAssertThrowsError
,XCTAssertNoThrow
팁
XCTAssertTrue, XCTAssertFalse
Testing Errors
XCTAssertThrowsError
,XCTAssertNoThrow
throws
키워드를 붙인 후, 마찬가지로 위 테스트 메소드를 사용한다.View controller testing
viewcontroller에서 테스트하는 것들
viewcontroller를 호출하는 방법
viewDidLoad
호출하기 (viewcontroller 초기화함수에 UI 초기화하기)Allow testing Host Application APIs
를 체크하면 테스트 작업을 실행할 때, 시뮬레이터나 디바이스에서 호스트앱이 실행된다.viewDidLoad()
호출loadViewIfNeeded()
를 통해 view를 로드함 (이 메소드는 더 알아봐야할듯)Test ordering matters (테스트 케이스 순서 중요함)
Randomized order
Code coverage
Debugging tests
test breakpoints
커버리지 높이기
distance > 0
만 테스트가 되고 뒤 코드는 돌아가지 않는 경우가 있음정리