【问题标题】:OCMockObject mocking an instance methodOCMockObject 模拟实例方法
【发布时间】:2014-05-06 11:16:48
【问题描述】:

我是 OCMockObjects 的新手,正在尝试模拟 ACAccount 类的实例方法:

-(NSArray *)accountsWithAccountType:(ACAccountType *)accountType;

我在测试类中写了这段代码来初始化mockObject:

ACAccountStore *accountStore = [[ACAccountStore alloc] init];
id mockAccountStore = [OCMockObject partialMockForObject:accountStore];
[[[mockAccountStore stub] andReturn:@[@"someArray"]] accountsWithAccountType:[OCMArg any]];

//call the test method
[myClassInstance methodToTest];

在 myClass 中,methodToTest 如下所示:

 -(void) methodToTest
{
    ACAccountStore *accountStore = [[ACAccountStore alloc] init];
    ACAccountType* accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
    NSArray* expectedArray = [accountStore accountsWithAccountType:accountType];
   //Getting nil value to Array rather than the returned value in stub
}

知道我在这里做错了什么。谢谢。

【问题讨论】:

    标签: ios ocmock xctest


    【解决方案1】:

    您正在创建一个模拟,但您正在测试的方法不是使用模拟,而是使用原始 ACAccountStore 类的实例。

    如果您愿意,使methodToTest 可测试的最简单方法是让它接受一个 ACAccountStore 实例作为参数。

    - (void)methodToTestWithAccountStore:(ACAccountStore *)accountStore;
    

    那么你的测试看起来像这样:

    [myClassInstance methodToTest:mockAccountStore];
    

    这将遵循依赖注入模式。如果您不喜欢这种模式,您可以模拟 ACAccountStore 的 alloc 方法以返回您的模拟对象,但我总是担心模拟 alloc 可能产生的副作用,而是会建议为 ACAccountStore 创建一个工厂:

    @interface ACAccountStore (Factory)
    + (instancetype)accountStore;
    @end
    @implementation ACAccountStore
    + (instancetype)accountStore { return [[ACAccountStore alloc] init]; }
    @end
    

    如果你使用这种模式,你可以模拟你的工厂方法。

    【讨论】:

      【解决方案2】:

      Ben Flynn 是正确的,您需要一种将AccountStore 注入您正在测试的对象的方法。执行此操作的另外两种方法:

      1) 将accountStore 设为在初始化时设置的待测类的属性,然后在测试中使用模拟覆盖该属性。

      2) 创建一个类似-(ACAccountStore *)accountStore 的方法来初始化帐户存储,但在您的测试中模拟该方法:

      ACAccountStore *accountStore = [[ACAccountStore alloc] init];
      id mockAccountStore = [OCMockObject partialMockForObject:accountStore];
      [[[mockAccountStore stub] andReturn:@[@"someArray"]] accountsWithAccountType:[OCMArg any]];
      
      id mockInstance = [OCMockObject partialMockForObject:myClassInstance];
      [[[mockInstance stub] andReturn:mockAccountStore] accountStore];
      
      // call the test method
      [myClassInstance methodToTest];
      

      【讨论】:

      • 我喜欢这个想法,尽管它确实意味着您正在扩展 ACAccountStore 对象的范围。不过,这没什么大不了的。
      • 是的,我认为第二种方法基本上等同于OP的原始代码-它只是将初始化移动到您可以在测试时拦截的方法中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      相关资源
      最近更新 更多