Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that a view controller successfully dismissed with animation

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() {

    }

}
like image 284
Erika Avatar asked Dec 03 '25 20:12

Erika


1 Answers

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)

}
like image 168
Harry Che Avatar answered Dec 05 '25 11:12

Harry Che



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!