Class Foo is implemented in both MyApp and MyAppTestCase. One of the two will be used. Which one is undefined

Class Foo is implemented in both MyApp and MyAppTestCase. One of the two will be used. Which one is undefined.

I wonder why is that?

because both images (the app and the unit test bundle) define the implementation of the class. the class is dynamically loaded into the objc runtime. the objc runtime uses a flat namespace. how this works:

  • the binary is loaded, starting with its dependencies
  • as each binary is loaded, the objc classes register with the objc runtime
  • if a class with a specific name is loaded twice, the behaviour is undefined. one implementation of a class (with identical names) can be loaded into the objc runtime.

the typical problem here is that you will be returned one implementation – your app will likely crash when the type conflicts (when the class does not come from the same source file).

you typically avoid this by either renaming a class, or export the class in one image. renaming the class obviously does not apply to your case. you have one file Foo.m which is being compiled, exported, and loaded by two images when it should be in one.

this should be interpreted by you as a duplicate symbol linker error. even though the implementation is the same source file (and the implementation is the same) – this a problem that you must fix.

How can I solve this?

if Foo.m is a class of the app, you have to remove (do not compile and link) Foo.m from the unit test. if it’s part of the unit test, then do not compile and link it into the unit test target.

then, follow the instructions in the post for linking/loading your unit test to the app. it’s in this general area of the post: where “WhereIsMyMac” is the name of the application you’re unit testing. This will let the testing target link against the application (so you don’t get linker errors when compiling). the important part is that your test files are compiled in the unit test target (only), and your app’s classes are compiled and linked into the app. you can’t just add them – they link and load dynamically.

Maybe I missed something when setting the unit test target?

From the article you linked:

Note: The testing target is a separate target. This means that you need to be careful of target membership. All application source files should be added to the application target only. Test code files should be added to the testing target only.

the part that you got wrong is probably the link and load phases of the unit test bundle.

Leave a Comment