samsung-ga / woody-iOS-tip

🐶 iOS에 대한 소소한 팁들과 개발하다 마주친 버그 해결기, 그리고 오늘 배운 것들을 모아둔 레포
19 stars 0 forks source link

TDD - Test Expresions #42

Open samsung-ga opened 2 years ago

samsung-ga commented 2 years ago

TDD - Test Expresions

레이먼드 아저씨 책 - iOS Test-Driven Development by Tutorials 의 네번째 챕터 Test Expressions에서 배운 내용

배운 내용

XCTAssert

종류

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

View controller testing

viewcontroller에서 테스트하는 것들

viewcontroller를 호출하는 방법

  1. Host App 사용하기
스크린샷 2022-09-12 오전 11 37 05
// 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
}
import UIKit
@testable import FitNess

extension RootViewController {
  var stepController: StepCountController {
    return children.first { $0 is StepCountController }
      as! StepCountController
  }
}
override func setUpWithError() throws {
  try super.setUpWithError()
  let rootController = getRootViewController() // ✅ 
  sut = rootController.stepController // ✅
}
  1. viewDidLoad() 호출
override func setUpWithError() throws {
  try super.setUpWithError()
  sut = StepCountController() // ✅
}

func testController_whenCreated_buttonLabelIsStart() {
  // given
  sut.viewDidLoad() // ✅

  // then
  let text = sut.startButton.title(for: .normal)
  XCTAssertEqual(text, AppState.notStarted.nextStateButtonLabel)
}
  1. 스토리보드를 통해 가져오기
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let stepController = storyboard.instantiateViewcontroller(withIdentifier: "stepController") as! StepCountController
stepController.loadViewIfNeeded()  // ✅

Test ordering matters (테스트 케이스 순서 중요함)

Randomized order

original-2

Code coverage

original 스크린샷 2022-09-12 오후 12 37 04 original-3

Debugging tests

test breakpoints

original-4

커버리지 높이기

var caught: Bool {
  return distance > 0 && nessie.distance >= distance
}

// ✅ 테스트 코드
func testModel_whenStarted_userIsNotCaught() {
  XCTAssertFalse(sut.caught)
}
func testModel_whenUserAheadOfNessie_isNotCaught() {
    // when
    sut.distance = 10000
    sut.nessie.distance = 100

    // then
    XCTAssertFalse(sut.caught)
}

func testModel_whenNessieAheadofUser_isCaught() {
    // given
    sut.nessie.distance = 1000
    sut.distance = 100

    XCTAssertTrue(sut.caught)
}

정리