I've had unit tests in my project for a couple weeks and they've been working fine up until now.

One of my new unit tests instantiates one of my custom view controllers. Said view controller instantiates and adds a subview of type CoolSearchBar, a class I've created myself (both .swift file and .xib file).

In said view controller, I load that CoolSearchBar instance programmatically, before adding it to the view hierarchy, like this:

guard let searchBar = Bundle.main.loadNibNamed(String(describing: CoolSearchBar.self), owner: nil, options: nil)?.first as? CoolSearchBar else {
    fatalError("Search bar could not be loaded from nib")
}

When I run the app normally, this check passes, and the rest of the code continues executing.

However, when I run my unit tests, the fatal error in the code above gets hit. I did some digging, and found that the reason why the error gets hit is that the class name alone (CoolSearchBar) does not tell the whole story.

Specifically, I used NSStringFromClass to get more verbose descriptions of the classes of the objects I'm comparing. Basically, the xib being created is evaluating to class type:

MyApp.CoolSearchBar

But the class that is being tested against (the as? CoolSearchBar part) is evaluating to:

MyAppTests.CoolSearchBar

Does anyone know why the module names vary on the classes? How I can get these two seemingly identical classes to evaluate to the same thing, so that my unit tests will pass again?

Thanks, and please comment if you need more information.

1 Answers

1
Mateus Forgiarini da Silva On Best Solutions

You probably added the CoolSearchBar to your test target as well. Uncheck your test from the target membership of your CoolSearchBar. If you want to access a class from the main application on your test project, import it by adding:

@testable import myApp

enter image description here

NOTE:

As Brian Sachetta had noticed. Once a class is removed from the target membership, all the others that make use of the class removed will start to complain. Therefore all the classes from the main project added to the test target membership will have to be removed from that membership.