objective-c - 如何使用 OCMock 初始化具有 stub 值的对象

标签 objective-c unit-testing ocmock

如何 stub init 方法中使用的方法?

我类的相关方法:

- (id)init
{
    self = [super init];
    if (self) {
        if (self.adConfigurationType == AdConfigurationTypeDouble) {
             [self configureForDoubleConfiguration];
        }
        else {
            [self configureForSingleConfiguration];
        }
    }
    return self;
}

- (AdConfigurationType)adConfigurationType
{
    if (adConfigurationType == NSNotFound) {
        if ((random()%2)==1) {
            adConfigurationType = AdConfigurationTypeSingle;
        }
        else {
            adConfigurationType = AdConfigurationTypeDouble;
        }
    }
    return adConfigurationType;
}

我的测试:

- (void)testDoubleConfigurationLayout
{
    id mockController = [OCMockObject mockForClass:[AdViewController class]];
    AdConfigurationType type = AdConfigurationTypeDouble;
    [[[mockController stub] andReturnValue:OCMOCK_VALUE(type)] adConfigurationType];

    id controller = [mockController init];

    STAssertNotNil([controller smallAdRight], @"Expected a value here");
    STAssertNotNil([controller smallAdRight], @"Expected a value here");
    STAssertNil([controller largeAd], @"Expected nil here");
}

我的结果:

由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“OCMockObject[AdViewController]:调用了意外的方法:smallAdRight”

那么我将如何访问 OCMockObject 中的 AdViewController?

最佳答案

如果您使用 mockForClass: 方法,您需要为模拟类中调用的每个方法提供 stub 实现。在你的第一个测试中包括你用 [controller smallAdRight] 调用它。

相反,您可以使用 niceMockForClass: 方法,该方法将忽略任何未模拟的消息。

另一种方法是实例化您的 AdViewController,然后使用 partialMockForObject: 方法为其创建部分模拟。这样 Controller 类的内部将完成主要部分的工作。

不过……您是要测试 AdViewController 还是使用它的类?看来您正在尝试模拟整个类(class),然后测试它是否仍然表现正常。如果您想测试 AdViewController 在注入(inject)某些值时是否按预期运行,那么最好的选择很可能是 partialMockForObject: 方法:

- (void)testDoubleConfigurationLayout {     
  AdViewController *controller = [AdViewController alloc];
  id mock = [OCMockObject partialMockForObject:controller];
  AdConfigurationType type = AdConfigurationTypeDouble;
  [[[mock stub] andReturnValue:OCMOCK_VALUE(type)] adConfigurationType];

  // You'll want to call init after the object have been stubbed
  [controller init]

  STAssertNotNil([controller smallAdRight], @"Expected a value here");
  STAssertNotNil([controller smallAdRight], @"Expected a value here");
  STAssertNil([controller largeAd], @"Expected nil here");
}

关于objective-c - 如何使用 OCMock 初始化具有 stub 值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7413920/

相关文章:

javascript - 在 UIWebView 中暂停 JavaScript 执行

c# - 使用 Entity Framework 将测试项目添加到 MVC

python - 在单元测试中比较 numpy float 数组

ios - OCMock单元测试错误

ios - OCMock 测试分配对象并调用方法

objective-c - 在 NSFetchRequest 中按实体名称排序

ios - 使用 performSelectorOnMainThread 将变量传递给其他方法

ios - 具有特定字符的 Unichar

java - 为了测试而将方法包或私有(private)化是不好的做法吗?

ios - OCMock 在被测代码中自动使用模拟实例?