Search code examples
iosobjective-cxctestreachabilityinternet-connection

XCTestCase with internet connection case


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?


Solution

  • 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];