본문 바로가기
Swift

Swift TCA Counter 예제 CounterStore 테스트하기

by mr.conan 2023. 7. 27.
728x90
반응형

 

이전글

2023.06.15 - [Swift] - Swift에서 TCA 아키텍처를 활용한 UIKit과 Combine을 사용한 Counter 예제

 

 

 

우리는 CounterStore 클래스를 테스트하기 위해 XCTest 프레임워크를 사용할 것입니다. 이 테스트 케이스는 CounterStore 클래스의 핵심 로직을 테스트하여 "increase"와 "decrease" 액션에 따른 count 값의 증가와 감소를 확인할 것입니다.

 

 

import XCTest
import Combine

@testable import MyCounterApp // 여기서 MyCounterApp은 프로젝트의 모듈 이름입니다. 실제 모듈 이름으로 대체해주세요.

class CounterStoreTests: XCTestCase {
    var counterStore: CounterStore!
    var cancellables: Set<AnyCancellable> = []

    override func setUp() {
        super.setUp()
        counterStore = CounterStore()
    }

    override func tearDown() {
        counterStore = nil
        cancellables.removeAll()
        super.tearDown()
    }

    func testIncreaseAction() {
        // Given
        let expectedCount = counterStore.state.count + 1
        
        // When
        counterStore.send(.increase)

        // Then
        XCTAssertEqual(counterStore.state.count, expectedCount, "Increase action should increase the count by 1")
    }

    func testDecreaseAction() {
        // Given
        let expectedCount = counterStore.state.count - 1

        // When
        counterStore.send(.decrease)

        // Then
        XCTAssertEqual(counterStore.state.count, expectedCount, "Decrease action should decrease the count by 1")
    }

    func testMultipleActions() {
        // Given
        let expectedCount = counterStore.state.count + 2

        // When
        counterStore.send(.increase)
        counterStore.send(.increase)

        // Then
        XCTAssertEqual(counterStore.state.count, expectedCount, "Multiple increase actions should increase the count by 2")
    }
}

 

 

위 테스트 코드를 보면, testIncreaseAction, testDecreaseAction, testMultipleActions라는 세 가지 테스트 메서드가 있습니다. 각 테스트 메서드는 특정 액션을 보냈을 때 CounterStore의 count 값이 기대한대로 증가하거나 감소하는지를 검증합니다. 테스트를 실행하기 위해서는 Xcode에서 테스트를 선택하고 실행하시면 됩니다.

테스트 코드를 작성함으로써, CounterStore 클래스의 동작을 검증하고 잠재적인 버그를 사전에 발견하는 데 도움이 됩니다. 또한, 테스트 코드는 코드 변경이나 리팩토링을 진행할 때 기존 기능들이 올바르게 동작하는지를 보장하는 데 큰 도움이 됩니다.

이상으로 Combine 프레임워크를 사용한 Counter 앱의 테스트 코드 작성 방법을 설명드렸습니다. 테스트 코드를 작성하고 실행함으로써 안정성과 확장성을 높이는 데 도움이 되었기를 바랍니다. 감사합니다!

728x90
반응형