isKindOfClass: returns false negative in unit test

2020-02-26 14:28发布

So I have an instance of MyViewController in the detail view of a UISplitViewController. I am running a unit test to see whether the detail view contains the correct type of view.

I test the type of controller in the unit test with the following:

[controller isKindOfClass:[MyViewController class]];

However, the isKindOfClass method always returns NO

When I po the object in the debugger I get the following:

(gdb) po controller
<MyViewController: 0xb31c4d0>

I have also tried the isMemberOfClass: method, it yields the same results. Can anyone explain why this would happen?

EDIT: So after reading the article posted by Nick Weaver I realised that I was including my app's source files in the test bundle's compile sources build phase. This was also indicated in the log by statements similar to following:

Class MyViewController is implemented in both /Users/jdoe/Library/Application Support/iPhone Simulator/4.3.2/Applications/670A077A-BAD8-4FA6-945A-851F33114CF5/MyApp.app/MyApp and /Users/jdoe/Library/Developer/Xcode/DerivedData/MyApp-drxyfejeattjwgantzesgensnlnx/Build/Products/Debug-iphonesimulator/MyAppTests.octest/MyAppTests. One of the two will be used. Which one is undefined.

However, when I remove the source files from the test bundle's compile sources build phase, I would get a linker error that looks like the following:

Undefined symbols for architecture i386:
"_OBJC_CLASS_$_MyViewController", referenced from:
  objc-class-ref in _MyViewControllerTests.o
 (maybe you meant: _OBJC_CLASS_$__MyViewControllerTests)

3条回答
混吃等死
2楼-- · 2020-02-26 15:14

As mentioned in my question, I realised I was incorrectly including the app's source files in the test bundle's compile sources build phase. After removing the source files from this build phase I solved the linker error of the missing symbols by changing the Symbols Hidden by Default build setting to "No" for the Debug configuration

Xcode build settings

This solved the linker error and meant that I was no longer including duplicate source files


Note: Also, be sure to set the "Host Target" for the test target in the Info tab of Xcode so it'll pull the compile sources from there

查看更多
做个烂人
3楼-- · 2020-02-26 15:25

Had the same issue with one of my apps, fixed it by removing .m file from Test target. In your case removing MyViewController.m from the test target will fix your issue. Open your .m file .Go to right navigator in Xcode and remove the tick from Target membership for test target. Problem is compiler compiles two MyViewController.m (one for app one for test) and .class may return different object.

查看更多
登录 后发表回答