[swift] Quick/Nimble을 사용한 UI 테스트 작성 방법

UI 테스트는 앱의 사용자 인터페이스의 동작을 테스트하고 검증하는 중요한 단계입니다. Swift에서는 Quick과 Nimble이라는 프레임워크를 사용하여 UI 테스트를 작성할 수 있습니다.

1. Quick 설치

먼저 Quick을 설치해야 합니다. CocoaPods를 사용하는 경우 Podfile에 다음과 같이 추가합니다:

target 'MyAppTests' do
  inherit! :search_paths
  pod 'Quick'
end

그리고 터미널에서 pod install 명령어를 실행하여 Quick을 설치합니다.

2. 테스트 작성

Quick을 사용하여 테스트 케이스를 작성할 수 있습니다. 테스트 파일은 Spec.swift와 같은 이름으로 생성합니다. 다음은 기본적인 테스트 케이스 작성 방법입니다:

import Quick
import Nimble
import UIKit

class MyViewControllerSpec: QuickSpec {
  override func spec() {
    describe("MyViewController") {
      var viewController: MyViewController!
      
      beforeEach {
        viewController = MyViewController()
      }
      
      it("should have a label") {
        expect(viewController.label).toNot(beNil())
      }
      
      it("should have the correct text in label") {
        expect(viewController.label.text).to(equal("Hello World"))
      }
      
      it("should have a button") {
        expect(viewController.button).toNot(beNil())
      }
      
      it("should trigger the correct action when button is tapped") {
        viewController.button.sendActions(for: .touchUpInside)
        expect(viewController.didTapButton).to(beTrue())
      }
    }
  }
}

위 예제는 MyViewController라는 뷰 컨트롤러의 기능을 테스트하는 예시입니다.

3. 테스트 실행

테스트를 실행하기 전에 XCTest 설정에서 Quick과 Nimble을 수용해야 합니다. XCTestCase의 후크 메서드를 사용하여 QuickSpec을 실행합니다.

import XCTest
import Quick

class Tests: XCTestCase {
  override class var defaultTestSuite: XCTestSuite {
    return XCTestSuite(name: "All tests") {
      QuickSpec.specs.forEach { spec in
        _ = spec.defaultTestSuite
      }
    }
  }
}

터미널에서 다음 명령어를 실행하여 테스트를 실행합니다:

$ xcodebuild test -scheme MyApp -destination 'platform=iOS Simulator,name=iPhone 12'

위 명령어에서 MyApp은 자신의 앱의 스킴으로 변경해야 합니다.

4. 결과 확인

테스트를 실행하면 콘솔에 성공 또는 실패한 테스트 결과가 표시됩니다.

Test Case '-' started.
MyViewController
  - should have a label
  - should have the correct text in label
  - should have a button
  - should trigger the correct action when button is tapped
✅ Executed 4 tests, with 0 failures (0 unexpected) in 0.123 (0.456) seconds

이제 Quick과 Nimble을 사용하여 UI 테스트를 작성하는 방법에 대해 알게 되었습니다. 테스트를 통해 앱의 사용자 인터페이스가 예상대로 동작하는지 확인할 수 있습니다. 자세한 내용은 Quick 및 Nimble 문서를 참조하시기 바랍니다.

참고 자료