【问题标题】:Verifying the order of method calls in Swift/XCTest验证 Swift/XCTest 中方法调用的顺序
【发布时间】:2018-05-15 07:46:24
【问题描述】:

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

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

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

【问题讨论】:

    标签: swift tdd xctest


    【解决方案1】:

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

    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])
    

    【讨论】:

      猜你喜欢
      • 2014-03-21
      • 2015-12-30
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      • 1970-01-01
      相关资源
      最近更新 更多