mercredi 2 septembre 2015

Mocking a String method in Swift

I've got some Swift 2.0 code, for which I'm trying to achieve 100% code coverage. I'm doing some JSON handling, part of which looks like so:

guard let jsonData = jsonText.dataUsingEncoding(NSUTF8StringEncoding) else {
    throw ErrorCode.JSONEncodingFailure
}

I don't think there's a real-world case in which any string can't be encoded as UTF-8, but I don't want to open myself up to a crashing error either, so that code must remain. How can I mock the jsonText object to return nil for dataUsingEncoding()?

The closest I've come is to subclass NSString like so:

public class BadString: NSString {

    public override var length: Int {
        get {
            return 5
        }
    }

    public override func characterAtIndex(index: Int) -> unichar {
        return  0
    }

    public override func dataUsingEncoding(encoding: NSStringEncoding) -> NSData? {
        return nil
    }

Here's the problem, though. In order for my mock implementation to be used, I have to define jsonText (a function parameter) as an NSString, rather than String, which feels wrong for an all-Swift codebase. With it defined as a Swift String, I have to cast my BadString to that type, and it uses the String implementation instead of my own.

Is there another (clean) way to achieve this?

Aucun commentaire:

Enregistrer un commentaire