mardi 26 avril 2016

iOS - Programmatically toggle internet connectivity from within Swift Unit Test

I'm writing a Unit Test in Swift 2 using XCode 7.3.

I'm trying to test a NetworkUtil class. One of the static methods #isNetworkConnected() checks whether or not a device has an active internet connection. The method body is below:

// Create a socket struct
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    // Set socket type to IPv4
    zeroAddress.sin_family = sa_family_t(AF_INET)


    // Can we reach an IPv4 address?
    guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
    }) else {
        return false
    }

    // Determines in-depth status of internet connectivity
    // Ex. isReachable, ConnectionRequired
    var flags : SCNetworkReachabilityFlags = []
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
        return false
    }

    let isReachable = flags.contains(.Reachable)
    let needsConnection = flags.contains(.ConnectionRequired)

    return (isReachable && !needsConnection)

I want to create highest possible code coverage. I'd like to set Wifi to ON, assert connectivity is true. Set Wifi to OFF, assert connectivity is false.

// TODO Set internet connectivity of Emulator
func testSuccessfulConnection() {
    // TODO Turn on WIFI
    let isConnected:Bool = NetworkUtils.hasNetworkConnection()
    XCTAssertTrue(isConnected, "Connected")
}

// TODO Set internet connectivity of Emulator
func testUnsuccessfulConnection() {
    // TODO Turn off WIFI
    let isConnected:Bool = NetworkUtils.hasNetworkConnection()
    XCTAssertFalse(isConnected, "Not Connected")
}

I understand that a production app will run with limited control of the underlying hardware. However, is there a way to programmatically manipulate the Wifi / Internet connectivity from within a Unit Test, if the hardware belongs to the Emulator?

Thanks!
Rob

Aucun commentaire:

Enregistrer un commentaire