如何从Swift项目中的测试中访问我的应用程序代码?

时间:2015-03-22 09:26:44

标签: xcode macos cocoa swift testing

我有一个Swift Xcode项目,其代码如下:

class Utils: NSObject {
    class func cleanString (input: String, trim: Bool) -> String {
        // ...
    }
}

然后我尝试测试它:

import XCTest

class AppTests: XCTestCase {
    func testConfiguratio() {
        Utils.cleanString("foo", trim: true)
    }
}

但是我收到了这个错误:

/Users/pupeno/Projects/macninja/AppTests/AppTests.swift:35:9: Use of unresolved identifier 'Utils'

我启用了Host Application API:

enter image description here

我错过了什么?

3 个答案:

答案 0 :(得分:1)

如前所述,库代码和测试代码是2个不同的模块。因此,您必须将库导入测试代码,并使您想要公开测试的函数,例如:

public class Utils: NSObject {
    public class func cleanString (input: String, trim: Bool) -> String {
        // ...
    }
}

import XCTest
import Utils

class AppTests: XCTestCase {
    func testConfiguratio() {
        Utils.cleanString("foo", trim: true)
    }
}

如果你想查看工作代码,请查看my IBANtools library project,它实现了这个场景(类函数,swift框架,大量测试)。

答案 1 :(得分:0)

包含测试的模块与包含应用代码的模块不同。如果要访问单独模块中包含的类,则需要确保将要导入的类标记为public

public class Utils: NSObject {
    class func cleanString (input: String, trim: Bool) -> String {
        // ...
    }
}

答案 2 :(得分:0)

如果这是OSX项目 - 请确保包括

@Testable import YOURPROJECTNAME

在'AppTests:XCTestCase'之上 并清理您的项目文件。

My Previous question where I had a similar issue is here

希望这会有所帮助(甚至一年后......)