admin管理员组文章数量:1394135
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.
本文标签: swiftError thrown in closure not caught in catch blockStack Overflow
版权声明:本文标题:swift - Error thrown in closure not caught in catch block - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744748026a2623005.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论