且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-09 09:58:58

库代码和测试代码是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)
}
}

如果您想查看工作代码,请查看我的IBANtools库项目它实现了这个场景(类函数,swift框架,大量的测试)。


I have an Swift Xcode project with code such as:

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

and then I try to test it:

import XCTest

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

but I get this error:

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

I have Host Application APIs enabled:

What am I missing?

As it has been said already, the library code and the test code are 2 different modules. So you have to import the library into the test code and also make the functions that you want to test public, e.g:

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

and

import XCTest
import Utils

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

If you want to see working code look at my IBANtools library project which implements exactly this scenario (class functions, swift framework, lots of testing).