简体   繁体   中英

Can I build a Unit Test for an External Service (iPhone)?

My app registers with an external service. The service phones me up with a two-digit code that I have to enter in (first time only) in order to use the service. The rest of the calls to the service work fine afterwards.

How would I set up a unit test for a method that isn't complete until a response code is entered out of band?

Any ideas? iOS SDK 4.2

Use OCMock to mock the service, that allows you to use stubbing and return the expected result.

For example:

Let's say this is your service:

@interface ServiceClass
- (NSString *) fetchData;
@end

This would be your mock service

id serviceMock = [[OCMockObject niceMockForClass:[ServiceClass class]];
[[[serviceMock stub] andreturn:@"56"] fetchData];
// we tell the mock to return the string "56" when the method fetchData is called

SomeViewController *mvc = [[SomeViewController alloc] init];
mvc.webService = serviceMock;
// Here we are injecting a mock into a view controller

You can use some Dependency injection techniques to inject this mock into your view controller

@synthesize webService = _webService;

- (IBAction)buttonClicked:(id)sender
{
   NSString *result = [self.webService fetchData];
}

- (ServiceClass *)webService
{
   if (!_webService)
   {
      _webService = [[ServiceClass alloc] init];
   }

   return _webService;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM