You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 05:17:04