【问题标题】:OCmock and MKReverseGeocoderOCmock 和 MKReverseGeocoder
【发布时间】:2010-05-04 15:34:00
【问题描述】:

我想测试一种使用反向地理编码的方法。我想做的是:

  • 将地理编码器设置为我的控制器的属性

  • 在init方法中创建地理编码器

  • 在我要测试的方法中调用地理编码器

  • 在我的测试中用模拟替换地理编码器

问题是MKReverseGeocoder坐标属性是只读的,我只能在构造方法中设置:

[[MKReverseGeocoder alloc] initWithCoordinate:coord]

当然,坐标仅在我想测试的方法中可用..

有谁知道我如何模拟 MKReverseGeocoder 类?

提前致谢, 文森特。

【问题讨论】:

    标签: ocmock mkreversegeocoder


    【解决方案1】:

    查看Matt Gallagher's great article on unit testing Cocoa applications。他为 NSObject 提供了一个类别扩展,允许您在测试时替换实例。我用它来做类似的事情。我认为您的测试看起来像这样:

    #import "NSObject+SupersequentImplementation.h"
    
    id mockGeocoder = nil;
    
    @implementation MKReverseGeocoder (UnitTests)
    
    - (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate {
       if (mockGeocoder) {
          // make sure the mock returns the coordinate passed in
          [[[mockGeocoder stub] andReturn:coordinate] coordinate];
          return mockGeocoder;
       }
       return invokeSupersequent(coordinate);
    }
    
    @end
    
    ...
    
    -(void) testSomething {
       mockGeocoder = [OCMockObject mockForClass:[MKReverseGeocoder class]];
       [[mockGeocoder expect] start];
    
       // code under test
       [myObject geocodeSomething];
    
       [mockGeocoder verify];
       // clean up
       mockGeocoder = nil;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 2011-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多