如何解决测试是否在 Objective C 的单元测试中调用了一个函数
在实现文件 (.mm) 中,我有一个函数根据在其他 API 中设置的布尔值 isTrue
的值调用不同的 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 或任何其他方式调用的函数 1?
解决方法
使用协议
@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
您将使用模拟来检查函数是否被调用
@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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。