WishIHadThreeGuns
WishIHadThreeGuns

Reputation: 1469

Testing topviewcontroller in a navigationcontroller

I want to use XCTest to unit test pushing on the stack.

So I perform a

XCTAssert(type(of: navigationController.topViewController) is DetailViewController.Type)

Which works if and only if I do not have animation enabled when I push the viewController.

self.navigationController!.pushViewController(vc, animated: false)

But within the viewController I want to test I have the animation enabled

self.navigationController!.pushViewController(vc, animated: true)

When the animation is enabled the type is the previous view controller's type.

I tried a sleep, and I tried using XCTWaiter i.e.

let result = XCTWaiter.wait(for: [expectation], timeout: 3.0)
        if result == XCTWaiter.Result.timedOut {
            XCTAssert(type(of: navigationController.topViewController) is DetailViewController.Type)
        } else {
            XCTFail("Delay interrupted")
        }

Unfortunately this does not work for me.

How can I test the navigation stack with animation enabled?

Upvotes: 2

Views: 1895

Answers (1)

Jon Reid
Jon Reid

Reputation: 20980

First, load your view controller, and put it into a navigation controller. No need for a UIWindow.

sut.loadViewIfNeeded()
let navigation = UINavigationController(rootViewController: sut)

Then have your test trigger whatever is supposed to push the new view controller.

Finally, to get this to register in the UINavigationController, execute the run loop once.

RunLoop.current.run(until: Date())

Then the test can investigate the stack in navigation.viewControllers.

Upvotes: 5

Related Questions