最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

swift - Error thrown in closure not caught in catch block - Stack Overflow

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论