在 Xcode 6.1 中运行测试时,一件烦人的事情是整个应用程序必须运行并启动其 Storyboard和 Root View Controller 。在我的应用程序中,这会运行一些获取 API 数据的服务器调用。但是,我不希望该应用在运行其测试时执行此操作。
随着预处理器宏的消失,什么是让我的项目知道它是运行测试而不是普通启动的最佳选择?我通常使用 command + U 在机器人上运行它们。
伪代码:
// Appdelegate.swift
if runningTests() {
return
} else {
// do ordinary api calls
}
最佳答案
如果您想拥有过去所谓的纯“逻辑测试”,Elvind 的答案还不错。如果您仍想运行包含主机应用程序但有条件地执行或不执行代码取决于是否运行测试,您可以使用以下方法检测是否已注入(inject)测试包:
if NSProcessInfo.processInfo().environment["XCTestConfigurationFilePath"] != nil {
// Code only executes when tests are running
}
我按照in this answer所述使用了条件编译标志这样运行时成本仅在调试构建中产生:
#if DEBUG
if NSProcessInfo.processInfo().environment["XCTestConfigurationFilePath"] != nil {
// Code only executes when tests are running
}
#endif
编辑 Swift 3.0
if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil {
// Code only executes when tests are running
}
关于ios - 如何让应用程序知道它是否在纯 Swift 项目中运行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27500940/