Codementor Events

Testing The Presentation Of A View Controller

Published Apr 01, 2019Last updated Apr 05, 2019
Testing The Presentation Of A View Controller

I’m writing a book about Test-Driven iOS Development with Swift. It’s not a traditional book, it’s mainly only the code. If you are like me and seldom read blog posts but rather skim for the code, this book is for you.

Let’s say we need to test if an action triggers the presentation of a view controller. The test looks like this:

func test_presentationOfViewController() {
  // Arrange 
  let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 300, height: 300)) 
  // sut == system under test 
  window.rootViewController = sut 
  window.makeKeyAndVisible() 
  
  // Act 
  sut.showNext() 
  
  // Assert 
  XCTAssertTrue(sut.presentedViewController is DetailViewController)
}

First we have to set the view controller (sut) that presents the other view controller as the rootViewController of a window. Then we need to make the window the key window. This way, the view of the view controller is added to the view hierarchy. If we miss the step, no other view controller can be presented on top of that view controller.

Next the presentation is triggered. How this is done, depends on the code under test. For simplicity, I assume that there is a method showNext() that triggers the presentation.

In the end we assert that the presented view controller has the expected type. Depending on the presented view controller, we could also assert that an expected item (user, point of interest, tweet, etc) has been passed to it.

That’s all. Straight forward. The tricky part is to remember to add the view controller under test as the root view controller to a window and make the window the key window.

Discover and read more posts from Dominik Hauser
get started
post commentsBe the first to share your opinion
Shelly Marshal
a year ago

Yes, that is correct. The first step is to set the view controller (sut) as the rootViewController of a window and make the window the key window. This adds the view of the view controller to the view hierarchy. Then, the presentation is triggered by calling the showNext() method. After this, the other view controller can be presented on top of the sut. Buy coursework online https://rapidessay.com/buy-coursework-online.html to simplify the process.

David Young
2 years ago

Thanks for sharing this presentation. Now I’m also preparing a presentation about the military. Master Bundles has proven to be quite helpful in doing this. Thanks to military PowerPoint templates, deal with the task much easier. The quality of my presentation improved and it became much brighter and more interesting.

Show more replies