LoginSignup
0
0

SwiftTestingで例外処理をテストする

Posted at

エラーがthrowされることをテストする

@Suite final class SampleTests {    
    @Test func throwErrorTest() throws {
        // なにかしらのエラーがthrowされることをテスト
        #expect(throws: (any Error).self) {
            try sample()
        }

        // SampleTestErrorがthrowされることをテスト
        #expect(throws: SampleTestError.self) {
            try sample()
        }

        // SampleTestError.hogehogeがthrowされることをテスト
        #expect(throws: SampleTestError.hogehoge) {
            try sample()
        }
    }
}

associatedValueの中身もテストする

@Suite final class SampleTests {    
    @Test func throwErrorTest() throws {
        #expect {
            try sample()
        } throws: { error in
            guard let error = error as? SampleTestError,
                  case let .fugafuga(code) = error
            else {
                return false
            }
            return code == 400
        }
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0