【问题标题】:Test if a function is called in Unit Testing for Objective C测试是否在 Objective C 的单元测试中调用函数
【发布时间】:2021-07-20 17:43:05
【问题描述】:

在实现文件 (.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 或任何其他方式调用了 function1?

【问题讨论】:

  • function1 实际上在做什么?您应该测试它应该做的任何事情都已完成,而不是检查函数本身是否被调用。因此,如果 function1function2 设置不同的属性,请测试是否在每种情况下都设置了适当的属性。
  • 是的,这是有道理的。 Function1 实际上设置了另一个变量的值。谢谢

标签: objective-c unit-testing ocmock xctestcase


【解决方案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);

}

【讨论】:

    猜你喜欢
    • 2016-08-07
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多