在实现文件(.mm(中,我有一个函数,它根据布尔isTrue
的值调用不同的API,该值在其他API 中设置
@implementation Controller
-(void) setProperty:(Id)Id value:(NSObject*)value
{
if(value) {
if(self.isTrue) {
[self function1]
} else {
[self function2]
}
}
}
现在我需要编写一个测试,对于isTrue的不同值,我需要测试是否调用了正确的函数。
我写了一些类似的东西:
-(void) testCaseforProperty
{
_controller.isTrue = true;
_controller setProperty:0 value:@YES];
// I need to check if function1 is called here
}
有人能告诉我如何在这里写一个测试来代替注释吗?以便测试这里用OCMock或XCTest或任何其他方式调用function1吗?
使用协议
@protocol FunctionsProviding
- (void)function1;
- (void)function2;
@end
您正在测试的对象可能如下所示:
@interface Controller: NSObject<FunctionsProviding>
@end
@interface Controller ()
@property (nonatomic, weak) id<FunctionsProviding> functionsProvider;
@property (nonatomic, assign) BOOL isTrue;
- (void)function1;
- (void)function2;
@end
@implementation ViewController
- (void)function1 {
//actual function1 implementation
}
- (void)function2 {
//actual function2 implementation
}
-(void) setProperty:(id)Id value:(NSObject*)value
{
if(value) {
if(self.isTrue) {
[self.functionsProvider function1];
} else {
[self.functionsProvider function1];
}
}
}
- (instancetype)init {
self = [super init];
if (self) {
self.functionsProvider = self;
return self;
}
return nil;
}
- (instancetype)initWithFunctionsProvider:(id<FunctionsProviding> )functionsProvider {
self = [super init];
if (self) {
self.functionsProvider = functionsProvider;
return self;
}
return nil;
}
@end
您可以使用mock来检查函数是否被称为
@interface FunctionsProviderMock: NSObject<FunctionsProviding>
- (void)function1;
- (void)function2;
@property (nonatomic, assign) NSUInteger function1NumberOfCalls;
@property (nonatomic, assign) NSUInteger function2NumberOfCalls;
@end
@implementation FunctionsProviderMock
- (void)function1 {
self.function1NumberOfCalls += 1;
}
- (void)function2 {
self.function2NumberOfCalls += 1;
}
@end
测试可能是这样的:
- (void)test {
FunctionsProviderMock *mock = [FunctionsProviderMock new];
Controller *sut = [[Controller alloc] initWithFunctionsProvider: mock]];
sut.isTrue = true;
[sut setProperty:0 value:@YES];
XCTAssertTrue( mock.function1NumberOfCalls, 1);
XCTAssertTrue( mock.function2NumberOfCalls, 1);
}