我是 iOS 开发新手,我正在尝试为我的代码编写单元测试。我需要访问实例变量。唯一的方法是创建一个类别,编写 getter 方法,然后将其导入到我的测试文件中吗?
这是我的 .m 文件
//imports
@implementation viewController{
NSArray* a;
int b;
//other variables
}
//methods
这是测试文件
#import "ViewController_Tests.h"
#import "ViewController.h"
@implementation ViewController_Tests{
ViewController *controller;
}
- (void)setUp {
[super setUp];
controller = [[ViewController alloc] initWithNibName:nil bundle:nil];
}
- (void)tearDown {
[super tearDown];
}
- (void)test1 {
NSArray* a;
//I want to access the variables here!
}
@end
最佳答案
我可以看到您可以使用的两种解决方案:
1:使用UISpec框架测试 View Controller 的功能,例如“断言 View Controller 有一个包含 X 个条目的表格 View ”(这是一个回归测试)并在具有完整 GUI 的模拟器中运行。
2:使用预编译器标志(例如#ifdef UNIT_TESTS)来打开对成员变量的访问或添加访问器方法,使用build设置在其他预处理器标志中定义UNIT_TESTS,因此它仅在单元测试中编译。
关于iOS 单元测试实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17984267/