Search code examples
swiftunit-testingxcode7.1beta

How to test required init(coder:)?


In my custom class WLNetworkClient I had to implement such method:

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

I do not need to use that, but I would like to test this to make 100% code coverage. Do you know how to achieve this?

I tried following way with no success:

let nc = WLNetworkClient(coder: NSCoder())
XCTAssertNotNil(nc)

Solution

  • Production code:

    required init?(coder: NSCoder) {
        return nil
    }
    

    Test:

    func testInitWithCoder() {
        let archiverData = NSMutableData()
        let archiver = NSKeyedArchiver(forWritingWithMutableData: archiverData)
        let someView = SomeView(coder: archiver)
        XCTAssertNil(someView)
    }
    

    Since the required initializer returns nil and does not use the coder, the above code can be simplified to:

    func testInitWithCoder() {
        let someView = SomeView(coder: NSCoder())
        XCTAssertNil(someView)
    }