Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test class for Swift project

I created a new Single view Swift project and create a 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'

enter image description here

As you see, import TextCase (my target) didn't solve the problem. The only way to solve the problem is to add MyModel.swift to 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). Is this a bug or a design?

like image 261
Bagusflyer Avatar asked Jul 24 '14 03:07

Bagusflyer


People also ask

How do I create a unit test in Swift?

To create new unit case in iOS, go to File -> New -> File, and then select Unit Test Case Class. Doing so creates a template just like the one you got with your project. In our case, we want to name the file to correspond with the new Pokemon-related data structures we have introduced.

How do I add unit tests to an existing Xcode project?

To add a unit test target to an existing Xcode project, choose File > New > Target. Select your app platform (iOS, macOS, watchOS, tvOS) from the top of the New Target Assistant. Select the Unit Testing Bundle target from the list of targets.

How do I write unit tests in Xcode?

Adding a unit test in Xcode These include both Unit Tests and UI Tests. If you already have a project, you can add a Unit Testing Bundle to it as well. Go to File > New > Target. Select iOS Unit Testing Bundle and then click Next.


1 Answers

You should add the swift file you are testing to the testing target.

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

add testing target to swift file

No need to change the access modifier to public, internal will do.


UPDATE

As of XCode 7 there is no need to make any file member of the testing target any more.

The recommended way is to use @testable import {Product Module Name}. Just make sure to use the product module's and not the projects' folder name.

like image 98
Filip Hermans Avatar answered Oct 26 '22 07:10

Filip Hermans