Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 693
Bartłomiej Semańczyk Avatar asked Sep 10 '15 11:09

Bartłomiej Semańczyk


1 Answers

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)
}
like image 80
Rudolf Adamkovič Avatar answered Sep 21 '22 16:09

Rudolf Adamkovič