Xcode 16 Swift Testing:调用辅助函数时SourceLocation如何设默认值?
在Swift测试辅助函数中自动获取调用处的SourceLocation(类似XCTAssert的行为)
要实现无需手动传入SourceLocation,同时让失败定位指向调用辅助函数的测试用例行,你需要利用Swift的编译字面值(#file、#line等)作为默认参数,让位置信息在调用处而非函数定义处求值。
修改后的辅助函数代码
private func test(state: State, against expectedState: State, file: StaticString = #file, line: UInt = #line) { // 此处执行若干无关检查 #expect(something == somethingElse, sourceLocation: SourceLocation(file: file, line: line)) }
如果你的SourceLocation支持列号参数,还可以补充#column:
private func test(state: State, against expectedState: State, file: StaticString = #file, line: UInt = #line, column: UInt = #column) { // 此处执行若干无关检查 #expect(something == somethingElse, sourceLocation: SourceLocation(file: file, line: line, column: column)) }
原理说明
你之前的写法sourceLocation = SourceLocation()会在函数定义的位置初始化SourceLocation,导致所有失败提示都指向辅助函数内部。而将#file、#line作为默认参数时,这些编译字面值会在函数被调用的位置求值,自动捕获调用处的文件路径和行号,再传递给SourceLocation,最终让#expect的失败提示定位到实际调用测试辅助函数的测试用例行,和XCTAssert系列方法的行为完全一致。
内容的提问来源于stack exchange,提问作者Lucas van Dongen
相关产品推荐
相关产品推荐

