我用 XCTestCase 编写单元测试用例,并在 -setUp 中初始化变量如下:
- (void)setUp {
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_myPath = @"Path";
});
}
但是当我尝试在测试用例中使用 myPath 时,它只适用于第一个,并且“myPath”在后续用例中将为零。
所以我在 -setUp 中设置了断点,看看会发生什么。我发现它为每种方法创建了新实例!!
为了仔细检查,我创建了一个新项目和测试目标来记录测试用例地址,如下所示:
@implementation fooTestTests
- (void)setUp
{
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
NSLog(@"<fooTestTests: %p>", self);
}
- (void)tearDown
{
// Put teardown code here. This method is called after the invocation of each test method in the class.
[super tearDown];
}
- (void)testExample
{
XCTFail(@"No implementation for \"%s\"", __PRETTY_FUNCTION__);
}
- (void)testExample2
{
XCTFail(@"No implementation for \"%s\"", __PRETTY_FUNCTION__);
}
@end
结果是:
fooTest[846:303] <fooTestTests: 0x1005ab750>
fooTest[846:303] <fooTestTests: 0x1005ab7f0>
由于 XCTestCase 被设计为具有一个或多个测试方法的对象,因此不应为每个方法创建不同的实例。
在这种情况下,我不知道在哪里设置我的测试环境。即使在 -init 中编写设置代码,它仍然会创建新实例并多次调用 -init。目前,我只有几个单元测试,但是当测试数量增加,并且设置过程变得更加复杂时,这将是一个问题。谁能给我一个建议?
添加问题摘要:
如果我在一个测试用例类中有 2 个测试方法,则行为将是:
- 将新测试用例实例化为对象 1
- -设置
- 测试 1
- -拆除
- 将新测试用例实例化为对象 2
- -设置
- 测试 2
- -拆除
为什么需要第 5 步?
答案
乔恩·里德提供的答案
更多信息: