2

I am very new to iOS dev and I am trying to write a unit test case for a class. It only has one method called homeButtonTouched() that dismisses the view controller with an animation. How may I write a unit test for this? This is what the class looks like.

class AboutViewController: UIViewController {

    // MARK: Action
    @IBAction func homeButtonTouched(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
}

This is what I have written so far in my test class. All I need is to fill out the testHomeButtonTouched() method.

class AboutViewControllerTests: XCTestCase {

    var aboutViewController: AboutViewController!

    override func setUp() {
        aboutViewController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "About View Controller") as! AboutViewController
        aboutViewController.loadView()

        super.setUp()
    }

    override func tearDown() {
        aboutViewController = nil

        super.tearDown()
    }

    /** Test that pressing the home button dismisses the view controller */
    func testHomeButtonTouched() {

    }

}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Erika
  • 235
  • 4
  • 12
  • Why would you want to test UI and view controller presentation with unit tests ? You can use UI testing for such things. – Sandeep Jan 07 '18 at 04:27
  • Like I said, I am very new to testing. Your input is helpful, though, thank you! – Erika Jan 07 '18 at 12:13

2 Answers2

4

You can create a mock class and override any func call of the original class to test if that func has been called. Such as this:

func test_ShouldCloseItself() {
    // mock dismiss call
    class MockViewController: LoginViewController {
        var dismissCalled = false
        override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
            self.dismissCalled = true
        }
    }

    let vc = MockViewController()
    vc.actionClose(self)
    XCTAssertTrue(vc.dismissCalled)

}
Harry Che
  • 171
  • 1
  • 8
1

Use UI testing for this. Create a new test file by going File->New->Target->iOS UI Testing Bundle.

Run the test script with Cmd+U. Then use the red record button above the console to automatically record a test, all you need to do at this point is dismiss the view controller using the simulator and xcode will write a test for you.

To answer your question though, if you want to check that your view controller was dismissed you could write an assert to check if it's the currently presented view controller like so:

if var topController = UIApplication.shared.keyWindow?.rootViewController {
  while let presentedViewController = topController.presentedViewController {
    topController = presentedViewController
  }
XCTAssertTrue(!topController is AboutViewController)
}
Cameron Porter
  • 801
  • 6
  • 15