Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of undeclared type 'ViewController' when unit testing my own ViewController in Swift?

Tags:

swift

xctest

I have been trying to write test cases in Swift to test my ViewController. However, when I try to instantiate my own ViewController in a XCTestCase I get "Use of undeclared type 'ViewController' ". (ViewController is the name of my own UIViewController class)

enter image description here

Has anyone else faced this issue before? I am using Xcode 6 beta 5

like image 851
hoomi Avatar asked Aug 14 '14 10:08

hoomi


2 Answers

Swift 1

You should add ViewController.swift file's target membership also as your test target also if you are not using framework. Select class file add to target as shown in image:

enter image description here

OR

If you are ViewController is within a framework : ViewController class is in different target and You are not declaring class with public access level. By default Classes are internal (Accessible within a target). Declare it as public and also make methods or properties as public if you want to access it i.e

public class ViewController: UIViewController {      public var content: String!      override public func viewDidLoad() {         super.viewDidLoad()         // Do any additional setup after loading the view, typically from a nib.     }      override public func didReceiveMemoryWarning() {         super.didReceiveMemoryWarning()         // Dispose of any resources that can be recreated.     }  } 

Swift 2 Update

In your test target, just import the module you want to test using the @testable keyword:

@testable import moduleToTest 

You can now access public and internal symbols in your test target.

swift 2 Xcode 7 unit testing

like image 106
Yatheesha Avatar answered Sep 30 '22 20:09

Yatheesha


I also got this error recently and none of the above steps fixed the problem, what did fix it was removing non-swift file from the Compile sources build phase in the Target you want to run tests on.

Make sure your app is actually compiling. This was failing silently and the error message wasn't helpful

enter image description here

like image 20
amleszk Avatar answered Sep 30 '22 21:09

amleszk