繁体   English   中英

测试目标 C 的单元测试中是否调用了 function

[英]Test if a function is called in Unit Testing for Objective C

在实现文件(.mm)中,我有一个 function 调用不同的 API,具体取决于在其他 API 中设置的 boolean isTrue的值

@implementation Controller

-(void) setProperty:(Id)Id value:(NSObject*)value
{
   if(value) {
      if(self.isTrue) {
         [self function1]
      } else {
         [self function2]
      }
   }
}

现在我需要编写一个测试,对于不同的 isTrue 值,我需要测试是否调用了正确的 function。

我写了类似的东西:

-(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

您正在测试的 object 可能如下所示:

@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

您将使用模拟来检查是否调用了 function

@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);

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM