Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test deinit of viewController

I want to test if I remove all the key value observers in the deinit of my view controller.

In the test class I have defined following method to start view controller lifecycle

  func startLifecycle() {
   _ = viewController.view
  }

In my test method I'm trying to invoke deinit by simply assigning nil to my view controller instance

testViewController = nil
XCTAssert for stuff...

But deinit is not called when I execute my test. I see no obvious retain cycles in my VC's code, what's more when I run the code in my app, not the test environment, deinit is called so it doesn't seem like something is keeping view controller in memory.

What is the correct way to release a view controller when testing?

like image 984
66o Avatar asked Dec 07 '15 15:12

66o


1 Answers

Try smth like this

class ViewController: UIViewController {
    var deinitCalled: (() -> Void)?
    deinit { deinitCalled?() }
}

class ViewControllerTest: XCTestCase {
    func test_deinit() { 
        var instance: ViewController? = ViewController()
        let exp = expectation(description: "Viewcontroller has deinited")
        instance?.deinitCalled = {
            exp.fulfill()
        }

        DispatchQueue.global(qos: .background).async {
            instance = nil
        }

        waitForExpectations(timeout: 2)
    }
}
like image 167
Anton Avatar answered Oct 12 '22 23:10

Anton