How to check required init (coder :)?

In my custom WLNetworkClient class WLNetworkClient I had to implement a method like this:

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

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

I tried the following path without success:

 let nc = WLNetworkClient(coder: NSCoder()) XCTAssertNotNil(nc) 
+6
source share
4 answers

Product 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 an encoder, the above code can be simplified to:

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

Here is an answer that should help you:

 let cd = NSKeyedUnarchiver(forReadingWithData: NSMutableData()) let c = CustomTextField(coder:cd) 
+1
source

From Rudolf Adamkovič is still working with Swift 4:

 required init?(coder aDecoder: NSCoder) { return nil } func testInitWithCoder() { // 1. Arrange let archiver = NSKeyedArchiver(forWritingWith: NSMutableData()) // 2. Action let viewController = ViewController(coder: archiver) // 3. Assert XCTAssertNil(viewController) } 
+1
source

I combined Rudolph's answer with Liz's suggestion and ended up with the following solution:

 let viewController = SomeTableViewController( presenter: SomePresenterMock(), coder: NSKeyedUnarchiver(forReadingWith: Data())) XCTAssert(viewController?.tableView.numberOfSections == 1) 

The key point here is to use NSKeyedUnarchiver(forReadingWith: Data()) as a dummy encoder, otherwise the test exits with an NSInvalidArgumentException .

+1
source

All Articles