1
Help us understand the problem. What are the problem?

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

.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()が呼ばれているかどうかテストすることができる。

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
1
Help us understand the problem. What are the problem?