Swift中的单元测试fatalError [英] Unit Test fatalError in Swift

查看:86
本文介绍了Swift中的单元测试fatalError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Swift中为fatalError代码路径实现单元测试?

How to implement unit test for a fatalError code path in Swift?

例如,我有以下快速代码

For example, I've the following swift code

func divide(x: Float, by y: Float) -> Float {

    guard y != 0 else {
        fatalError("Zero division")
    }

    return x / y
}

我想对y = 0时的情况进行单元测试.

I want to unit test the case when y = 0.

请注意,我要使用fatalError而不是其他任何断言函数.

Note, I want to use fatalError not any other assertion function.

推荐答案

灵活 (用于Swift和Objective-C的Matcher框架")得到了支持:

Nimble ("A Matcher Framework for Swift and Objective-C") got your back :

快速断言

如果您使用的是Swift,则可以使用throwAssertion匹配器检查是否抛出了断言(例如fatalError()).这是通过@mattgallagher的CwlPreconditionTesting库实现的.

If you're using Swift, you can use the throwAssertion matcher to check if an assertion is thrown (e.g. fatalError()). This is made possible by @mattgallagher's CwlPreconditionTesting library.

// Swift

// Passes if 'somethingThatThrows()' throws an assertion, 
// such as by calling 'fatalError()' or if a precondition fails:
expect { try somethingThatThrows() }.to(throwAssertion())
expect { () -> Void in fatalError() }.to(throwAssertion())
expect { precondition(false) }.to(throwAssertion())

// Passes if throwing an NSError is not equal to throwing an assertion:
expect { throw NSError(domain: "test", code: 0, userInfo: nil) }.toNot(throwAssertion())

// Passes if the code after the precondition check is not run:
var reachedPoint1 = false
var reachedPoint2 = false
expect {
    reachedPoint1 = true
    precondition(false, "condition message")
    reachedPoint2 = true
}.to(throwAssertion())

expect(reachedPoint1) == true
expect(reachedPoint2) == false

注意:

  • 此功能仅在Swift中可用.
  • 仅x86_64二进制文件支持此功能,这意味着您不能在iOS设备上运行此匹配器,而只能在模拟器上运行.
  • 支持tvOS模拟器,但是使用了不同的机制,要求您关闭tvOS方案的测试"配置的调试"可执行方案设置.
  • This feature is only available in Swift.
  • It is only supported for x86_64 binaries, meaning you cannot run this matcher on iOS devices, only simulators.
  • The tvOS simulator is supported, but using a different mechanism, requiring you to turn off the Debug executable scheme setting for your tvOS scheme's Test configuration.

这篇关于Swift中的单元测试fatalError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆