I'm trying to test that a error thrown in a function, is properly caught. I have the following code:
// package A
public enum SomeError: Int, Error {
case errorOne = 1
case errorTwo = 2
}
package B
struct SomeStruct {
let service: SomeService
func functionThatShouldCatch() throws -> String {
do {
let result = try service.getSomething()
} catch SomeError.errorOne {
// Should catch here
}
return "All ok"
}
}
Mock:
class MockService: Service {
var getSomethingHandler: (() throws -> String)? = nil
}
Testing it all:
@Test func testingAllOk() throws {
mockService.getSomethingHandler = { throw SomeError.errorOne }
let result = try sut.functionThatShouldCatch() // <- Test fails here, catching the error gives SomeError.errorOne
#expect(result == "All ok")
}
I'm skipping some parts to only show the important parts.
Is my setup wrong, or is throwing an Error from an external package in a closure like this not working?
When doing this in the SomeStruct:
func functionThatShouldCatch() throws -> String {
do {
let result = try service.getSomething()
} catch SomeError.errorOne {
// Should catch here
} catch {
print(error) // <- Shows SomeError.errorOne
}
return "All ok"
}
UPDATE
What I've found out that the location of SomeError seems to matter.
When SomeError is in the same package as where the Error should be caught, it works. (I can throw it in the test and it will be caught). When the Error is in a separate package, it doesn't work. Renaming didn't make a difference.
Strange is that it does work when the app is running, it only fails in the tests.