Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing network calls (failing tests) - Swift

I'm trying to write failing tests for my network calls but can't find anyway to access the connection settings from within my tests.

This code works fine for testing a success case:

func testRetrieveProducts() {

    let expectation = expectationWithDescription("asynchronous request")

    Requests().retrieveProducts({ (products) -> () in

        // check that we have two arrays returned.
        XCTAssert(products.count == 2)
        expectation.fulfill()

        }) { (error) -> () in
        XCTFail("Request failed")
    }
    waitForExpectationsWithTimeout(5.0, handler: nil)
}

But I've been looking for a way to test network timeouts, and incorrect data being returned.

I can probably test incorrect data by calling functions individually inside the retrieveProducts function and stubbing stuff out, but doing something as simple as turning off the internet is proving to be quite difficult.

I know we have access to the Network Link Conditioner, but turning this on and off for each test isn't an option.

I'd love to have access to something as simple as:

func testFailRetrieveProducts() {

    let expectation = expectationWithDescription("asynchronous request")
    SomeNetworkClass.disableInternet()

    Requests().retrieveProducts({ (products) -> () in

        }) { (error) -> () in
        XCTAssert(error == SomeError.TimeoutError)
    }
    waitForExpectationsWithTimeout(5.0, handler: nil)
}

Any solutions out there that can handle what I'm after, or am I going about this all wrong?

like image 645
Beau Nouvelle Avatar asked Nov 26 '25 21:11

Beau Nouvelle


1 Answers

Take a look at this NSHipster article about Apple's Network Link Conditioner. There's a lot of presets and you can create your own custom network profile. Unfortunately there doesn't seem to be a way to throttle the network in code.

A somewhat viable alternative however is to use ReactiveCocoa and model all your network events as SignalProducers. Then you can use the throttle or wait function, depending on your intentions.

like image 77
barndog Avatar answered Nov 29 '25 15:11

barndog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!