3

I'm writing an app that has separated functions when online and offline. In those function, I use Reachability to check internet connection and with each case (online/offline), it does different works.

Now, I've been required to write test cases for those business logics. I've searched everywhere, but it seems that no one care much about test case in iOS.

I'd like to write testcase that cover for both online/offline case. Does it possible in iOS? If so, how do I simulate the internet connection status?

UPDATE QUESTION:

I also want to cover the case switching from online to offline and vice versa. There should be a way to simulate this network connection status, right?

Eddie
  • 1,903
  • 2
  • 21
  • 46
  • This might be helpful: [What is mocking?](http://stackoverflow.com/questions/2665812/what-is-mocking), [OCMock](http://ocmock.org). – FreeNickname May 31 '16 at 07:48

1 Answers1

3

You should mock return value using OCMock

id reachabilityMock = OCMClassMock([Reachability class]);
[OCMStub([reachabilityMock currentReachabilityStatus]) andReturnValue:@(ReachableViaWiFi)];
[OCMStub([reachabilityMock reachabilityForInternetConnection]) andReturn:reachabilityMock];
Reachability *reachability = [Reachability reachabilityForInternetConnection];
XCTAssertEqual(reachability.currentReachabilityStatus, ReachableViaWiFi);

Then send reachability changed notification manually.

[[NSNotificationCenter defaultCenter] postNotificationName: kReachabilityChangedNotification object: noteObject];
Bing
  • 351
  • 3
  • 12
  • Hi, sorry for the late comment. I have a static singleton object, which hold an instance of `Reachability` to check internet changes. That object is being initialized alongside with reachability object **BEFORE** the test setup, so the mock doesn't work with its property. How can I work around this? – Eddie Jun 06 '16 at 09:16
  • You may need to use method swizzling to mock before the singleton initialized. – Bing Jun 08 '16 at 05:05
  • Thanks, I'll contact you later after testing method swizzling. It looks nice. – Eddie Jun 08 '16 at 09:20