问题描述
我查看了很多博客并尝试了很多方法来让我的 Swift 单元测试在 Xcode 6.0.1(或 6.1 就此而言)中工作.我正在尝试访问我的应用程序目标中的类,所以我写了这一行:
I have looked at a lot of blogs and tried many things to get my Swift unit tests to work in Xcode 6.0.1 (or 6.1 for that matter). I'm trying to access classes in my app's target so I wrote this line:
var vc: LoginViewController!
当然,我收到了使用未声明的类型‘LoginViewController’"错误.
Of course, I get the "Use of undeclared type 'LoginViewController'" error.
然后我尝试将 LoginViewController
添加到我的测试目标,但随后我在我的项目中的其他类上遇到使用未解析的标识符"错误.因此,我尝试将这些类添加到我的测试目标中,但最终出现了看似无穷无尽的错误源,如下面的屏幕截图所示:
I then try to add LoginViewController
to my test target, but then I get "use of unresolved identifier" errors on other classes in my project. So I try to add those classes to my test target, but I end up with a seemingly endless source of errors like the screenshot below:
将我的所有类声明为公共类会导致其他错误,并且似乎是不好的做法.无论如何要在依赖于许多框架和类的 Swift 项目中包含单元测试吗?我只想从与这篇 文章.
Declaring all my classes as public, causes other errors and seems like bad practice. Is there anyway to include unit tests in a Swift project that relies on many frameworks and classes? I simply want to start with something almost exactly like the code in this article.
推荐答案
在很头疼并将这个问题搁置之后,我发现主要问题是在将文件添加到测试目标成员资格时,Objective-C 类会还在抱怨.我认为这是 Swift 进行单元测试的新方式的旧兼容性问题,但解决方案是我的测试目标不知道有桥接头.因此,我在测试目标的构建设置中添加了对它的引用,如下所示:
After much headache and putting this on the back burner, I found that the main problem was when adding files to the test target membership, the Objective-C classes would still complain. I figured it was an old compatibility issue with the new way Swift does unit tests, but the solution was my test target didn't know there was a bridging header. Thus, I added a reference to it in my test target's build settings, like so:
现在看起来简单明了,但错误无济于事.我在 Swift 单元测试中没有看到其他解决方案表明这可能是一个问题,但现在我知道了.
It seems simple and obvious now, but the errors were unhelpful. No other solutions I saw for Swift unit tests suggested this could be an issue, but now I know.
Tl;博士
要在 Swift 中进行单元测试,测试目标必须知道应用目标知道的一切,因此也要在测试目标中添加对桥接头的引用(如果适用).
For unit tests to work in Swift, the test target must know everything the app target knows, so add a reference to your bridging header in your test target too (if applicable).
这篇关于将 Swift 文件添加到测试目标而不是修复单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!