在一个新项目中,我有这个简单的测试
#import <XCTest/XCTest.h>
#import "ViewController.h"
@interface ViewControllerTests : XCTestCase
@end
@implementation ViewControllerTests
- (void)testExample
{
// Using a class that is not in the test target.
ViewController * viewController = [[ViewController alloc] init];
XCTAssertNotNil(viewController, @"");
}
@end
Run Code Online (Sandbox Code Playgroud)
ViewController.h 不是测试目标的一部分,但它编译并运行测试没有任何问题.

我认为这是因为应用程序首先构建(作为依赖)然后是测试.链接器然后找出ViewController类是什么.
但是,在较旧的项目中,使用完全相同的测试和ViewController文件,构建在链接器阶段失败:
Run Code Online (Sandbox Code Playgroud)Undefined symbols for architecture i386: "_OBJC_CLASS_$_ViewController", referenced from: objc-class-ref in ViewControllerTests.o
即使创建了新的XCTest单元测试目标,也会发生此链接器错误.
为了解决这个问题,可以在应用程序和测试目标中包含源(勾选上图中的两个框).这会在模拟器的系统日志中导致重复符号的构建警告(打开模拟器并按cmd- /查看):
Run Code Online (Sandbox Code Playgroud)Class ViewController is implemented in both [...]/iPhone Simulator/ [...] /MyApp.app/MyApp and [...]/Debug-iphonesimulator/LogicTests.octest/LogicTests. One of the two will be used. Which one is undefined.
这些警告偶尔会导致以下示例说明的问题: …