验证 Swift/XCTest 中方法调用的顺序

Verifying the order of method calls in Swift/XCTest

我目前正在为我遇到的一个错误编写测试,其中生产代码中的调用顺序不正确,导致潜在的竞争条件。

使用 XCTest 检查测试代码调用顺序的最简洁方法是什么?

在 OCMock/Objective-C 中,我们有 setExpectationOrderMatters,根据 this question。但是,由于 dynamic/static 语言差异,我不知道 XCTest/Swift 中有类似的功能。

假设我们想模拟这个协议:

protocol Thing {
    func methodA()
    func methodB()
}

这是一个不仅记录各个方法的调用次数的模拟。它记录调用顺序:

class MockThing: Thing {
    enum invocation {
        case methodA
        case methodB
    }
    private var invocations: [invocation] = []

    func methodA() {
        invocations.append(.methodA)
    }

    func methodB() {
        invocations.append(.methodB)
    }

    func verify(expectedInvocations: [invocation], file: StaticString = #file, line: UInt = #line) {
        if invocations != expectedInvocations {
            XCTFail("Expected \(expectedInvocations) but got \(invocations)", file: file, line: line)
        }
    }
}

这支持如下测试断言:

mock.verify(expectedInvocations: [.methodA, .methodB])