在一个新项目中,我有一个简单的测试
#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
视图控制器.h是测试目标的not部分,但它编译并运行测试时没有任何问题.
我认为这是因为应用程序首先构建(作为一种依赖性),然后才进行测试.然后链接器计算出ViewController类是什么.
但是,在一个旧项目中,使用完全相同的测试和ViewController文件,构建在链接器阶段失败:
Undefined symbols for architecture i386: "_OBJC_CLASS_$_ViewController", referenced from: objc-class-ref in ViewControllerTests.o
即使在创建新的XCTest单元测试目标时,也会发生此链接器错误.
要解决此问题,可以将源代码同时包含在应用程序和测试目标中(勾选上图中的两个框).这会导致模拟器的系统日志(log)中出现重复符号的构建警告(打开模拟器并按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
因此,问题是旧项目中的哪些设置要求将应用程序源文件包括在测试目标中?
comments 摘要
在工作项目和非工作项目之间:
- 链接器输出没有区别(命令以
Ld
开始). - 目标依赖性没有差异(测试目标有1个依赖性,即应用程序)
- 链接器设置没有区别.