简体   繁体   English

Swift项目的单元测试类

[英]Unit test class for Swift project

I created a new Single view Swift project and create a MyModel : 我创建了一个新的单视图Swift项目并创建了一个MyModel

class MyModel {

    func add(a : Int, b : Int) -> Int {
        return a + b
    }
}

But I had a problem to create a test case. 但是我在创建测试用例时遇到了问题。 Error message: 错误信息:

/Volumes/Macintosh HD/Users/user/Projects/TestCase/TestCaseTests/TestCaseTests.swift:26:19: Use of unresolved identifier 'model' / Volumes / Macintosh HD / Users / user / Projects / TestCase / TestCaseTests / TestCaseTests.swift:26:19:使用未解析的标识符'model'

在此输入图像描述

As you see, import TextCase (my target) didn't solve the problem. 如您所见, 导入TextCase (我的目标)并没有解决问题。 The only way to solve the problem is to add MyModel.swift to target: TestCaseTests . 解决问题的唯一方法是将MyModel.swift添加到target: TestCaseTests But this is different from Objective-C project (I don't need to add the .m files to test case target at all). 但这与Objective-C项目不同(我根本不需要添加.m文件来测试案例目标)。 Is this a bug or a design? 这是一个错误还是一个设计?

You should add the swift file you are testing to the testing target. 您应该将正在测试的swift文件添加到测试目标中。

This can be done by clicking on the swift file, going to the Utilities panel (the one on the right) and checking the checkbox under "Target membership". 这可以通过单击swift文件,转到Utilities面板(右边的那个)并选中“Target membership”下的复选框来完成。

将测试目标添加到swift文件

No need to change the access modifier to public, internal will do. 无需将访问修饰符更改为public,内部就可以。


UPDATE UPDATE

As of XCode 7 there is no need to make any file member of the testing target any more. 从XCode 7开始,不再需要制作测试目标的任何文件成员。

The recommended way is to use @testable import {Product Module Name} . 建议的方法是使用@testable import {Product Module Name} Just make sure to use the product module's and not the projects' folder name. 只需确保使用产品模块而不是项目的文件夹名称。

根据这个答案,您现在可以使用@testable import {Module Name} (使用Xcode 7)。

Access modifiers had become available starting Beta 4, and the unit test class is now considered as outside the subject's module, so for it to access anything within your module, it has to be declared public . 从Beta 4开始,访问修饰符已经可用,单元测试类现在被认为是在主题模块之外,因此要访问模块中的任何内容,必须将其公开

public class MyModel {

    public func add(a : Int, b : Int) -> Int {
        return a + b
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM