I use the Swift Testing
framework in my iOS
project. Imagine I have a function I need to test:
func isEven(_ num: Int) -> Bool
I’m working with parameterized tests, where multiple test cases are evaluated using the same test function. I’d like Xcode to show the exact line of the failing test case, similar to how Issue.record works.
Here’s my current setup:
@Test(arguments: testCases)
func test() {
let output = isEven(testCase.input)
#expect(output == testCase.expectedOutput) // I need to somehow pass file and line here
}
static var testCases: [TestCase<Int, Bool>] = [
(2, true),
(0, true),
(3, false),
(5, true) // Incorrect expected value for demonstration
]
struct TestCase<Input, Output> {
public let input: Input
public let expectedOutput: Output
public let file: StaticString
public let line: UInt
public init(input: Input, expectedOutput: Output, file: StaticString = #file, line: UInt = #line) {
self.input = input
self.expectedOutput = expectedOutput
self.file = file
self.line = line
}
}
What I’m Trying to Achieve
- Xcode to report the exact file and line where the test case failed (In case of parametrised tests).
Question
- Is it possible to pass file and line to #expect in the Swift Testing framework?
- If not, is there an alternative way to achieve the desired behavior?
Any guidance would be appreciated!
2
Answers
#expect
takes asourceLocation:
parameter, which defaults to the location of the#expect
macro. You can replace it with your ownSourceLocation
.Your idea of taking in the line number in the initialiser of
TestCase
is in the right direction. Instead of the line number, take aSourceLocation
.Note the use of the
#_sourceLocation
macro to get the current source location. If you don’t like seeing underscore APIs for some reason, you can always take the 4 components of aSourceLocation
as parameter instead:The
#expect
can accept aSourceLocation
: