OCmock 和 MKReverseGeocoder

发布于 2024-08-31 10:27:59 字数 402 浏览 2 评论 0原文

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

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

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

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

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

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

[[MKReverseGeocoder alloc] initWithCoordinate:coord]

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

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

提前致谢, 文森特.

I would like to test a method that uses reverse Geocoding. What i would like to do is :

  • set the geocoder as a property of my controller

  • create the geocoder in the init method

  • call the geocoder in the method i want to test

  • replace the geocoder with a mock in my test

The problem is that the MKReverseGeocoder coordinate property is read only, i can only set it in the constructor method :

[[MKReverseGeocoder alloc] initWithCoordinate:coord]

And of course the coordinates are only available in the method i want to test..

Does anyone knows how i could mock the MKReverseGeocoder class ?

Thanks in advance,
Vincent.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌辣 2024-09-07 10:27:59

查看 Matt Gallagher 关于 Cocoa 应用程序单元测试的精彩文章。他为 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;
}

Check out Matt Gallagher's great article on unit testing Cocoa applications. He provides a category extension to NSObject that allows you to replace instances at test time. I've used it to do something similar. I think your test would look something like this:

#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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文