ridvankucuk
ridvankucuk

Reputation: 2407

Unit Test Coverage is below expected

I have written a basic Utilities class that has a method converts json to data.

static func data(from json: [String : AnyObject]) throws -> Data {
    do {
        return try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
    } catch let error {
        throw error
    }
}

After that I wrote some tests for this method.

func testJsonToDataSuccess() {
    let mockJson: [String : Any] = ["hello" : "there"]
    do {
        let data = try Utils.data(from: mockJson as [String : AnyObject])
        XCTAssertNotNil(data)
    } catch let error {
        XCTFail(error.localizedDescription)
    }
}

func testJsonToDataFail() {
    let someString = String(
        bytes: [0xD8, 0x00] as [UInt8],
        encoding: String.Encoding.utf16BigEndian)!

    let mockJson = ["hello" : someString]
    do {
        let data = try Utils.data(from: mockJson as [String : AnyObject])
        XCTAssertNil(data)
    } catch let error {
        XCTAssertNotNil(error)
    }
}

I assumed that I have tested both success and fail cases for this Utilities class. However test coverage for this class is: %85. I wonder that why the test coverage is not %100? Any help would be appreciated...

Upvotes: 0

Views: 304

Answers (1)

Patru
Patru

Reputation: 4551

Pheew, you gave me a tough time about this one, but I guess it was worth it to learn about code Coverage in Xcode. Once I got your code to run (which was not as easy as it should have been since you did not include instructions on what project setup you had used nor were your files complete) I finally got it to run as a MacOs application.

As you said the coverage of your Utils class (or the data function) would not end up being complete. If you check out the lines that have not been covered those will just be the final ones with the closing braces (at least that's what it ended up being in my case). This seems to be some rather annoying behaviour of Xcode, but if you check out this question this seems to be a long standing issue which to my knowledge has not been resolved.

Strangely enough this will go away once you rewrite your function as follows:

static func data(from json: [String : AnyObject]) throws -> Data {
    let data: Data
    do {
        data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
    } catch let error {
        throw error
    }
    return data
}

The final brace will not be hit with this behaviour.

However I grant you the title for the hardest piece of Swift-code I had to grock so far.

Upvotes: 1

Related Questions