在一个新项目中我有这个简单的测试
#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
ViewController.h 是not测试目标的一部分,但这可以毫无问题地编译和运行测试。
我认为这是因为应用程序是首先构建的(作为依赖项),然后是测试。然后链接器会找出 ViewController 类是什么。
但是,在较旧的项目中,使用完全相同的测试和 ViewController 文件,构建在链接器阶段失败:
Undefined symbols for architecture i386:
"_OBJC_CLASS_$_ViewController", referenced from:
objc-class-ref in ViewControllerTests.o
即使创建新的 XCTest 单元测试目标,也会发生此链接器错误。
为了解决这个问题,可以将源代码包含在应用程序和测试目标中(勾选上图中的两个框)。这会导致模拟器的系统日志中出现重复符号的构建警告(打开模拟器并按 cmd-/ 查看此内容):
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.
这些警告有时会导致以下示例所示的问题:
[viewController isKindOfClass:[ViewController class]]; // = NO
// Memory address of the `Class` objects are different.
NSString * instanceClassString = NSStringFromClass([viewController class]);
NSString * classString = NSStringFromClass([ViewController class]);
[instanceClassString isEqualToString:classString]; // = YES
// The actual class names are identical
所以问题是旧项目中的哪些设置要求应用程序源文件包含在测试目标中?
意见摘要
工作项目和非工作项目之间:
- 链接器输出没有区别(以
Ld
).
- 目标依赖项没有区别(测试目标有 1 个依赖项,即应用程序)
- 链接器设置没有区别。