Pablo Fernandez
Pablo Fernandez

Reputation: 287830

How do I access my app code from my tests in a Swift project?

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:

enter image description here

What am I missing?

Upvotes: 1

Views: 863

Answers (3)

UKDataGeek
UKDataGeek

Reputation: 6922

If this is an OSX project - make sure you included

@Testable import YOURPROJECTNAME

Above the 'class AppTests: XCTestCase'
and clean your project files.

My Previous question where I had a similar issue is here

Hope this helps ( even a year later...)

Upvotes: 2

Mike Lischke
Mike Lischke

Reputation: 53532

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).

Upvotes: 1

Paul Patterson
Paul Patterson

Reputation: 6928

The module that contains your tests is distinct from the module that contains your app code. When you want to access classes that are contained within a separate module you need to ensure that the to-be-imported classes are marked as public:

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

Upvotes: 0

Related Questions