LoginSignup
1
1

More than 1 year has passed since last update.

[Swift]対象のメソッドが呼ばれたかどうかをテストしたい

Posted at
.swift
final class Controller {
    private let useCaseInput: UseCaseInput

    init(useCaseInput: UseCaseInput) {
        self.useCaseInput = useCaseInput
    }

    func onHogeHogeButtonTapped() {
        useCaseInput.hogehoge()
    }
}

protocol UseCaseInput {
    func hogehoge()
}

final class UseCase: UseCaseInput {

    func hogehoge() {
        print("hogehoge")
    }
}

このようにクラスAがクラスBのメソッドを呼ぶコードがあり、テストで呼ばれているかを確認したい場合の対応法について書きます。

結論。インターフェースを使ってモックを作成し、テストを書けばいい。

.swift
final class MockUseCase: UseCaseInput {
    
    var isHogeHogeCalled = false
    func hogehoge() {
        isHogeHogeCalled = true
    }
}
Test.swift
import XCTest

final class ControllerTests: XCTestCase {

    override func setUpWithError() throws {
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDownWithError() throws {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
    }

    func test_hogehoge() throws {
        let useCase = MockUseCase()
        let controller = Controller(useCaseInput: useCase)

        useCase.onHogeHogeButtonTapped()
        XCTAssertEqual(useCase.isHogeHogeCalled, true)
    }
}

これでhogehoge()が呼ばれているかどうかテストすることができる。

例のコードが分かりにくかったらごめんなさい💦

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1