2

我对 iOS 开发人员非常陌生,我正在尝试为一个类编写一个单元测试用例。它只有一个名为 homeButtonTouched() 的方法,可以通过动画关闭视图控制器。我该如何为此编写单元测试?这就是班级的样子。

class AboutViewController: UIViewController {

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

这是我到目前为止在我的测试课上写的。我只需要填写 testHomeButtonTouched() 方法。

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

    }

}
4

2 回答 2

3

您可以创建一个模拟类并覆盖原始类的任何 func 调用以测试该 func 是否已被调用。比如这样:

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)

}
于 2019-04-09T22:07:13.523 回答
1

为此使用 UI 测试。通过 File->New->Target->iOS UI Testing Bundle 创建一个新的测试文件。

使用 Cmd+U 运行测试脚本。然后使用控制台上方的红色记录按钮自动记录测试,此时您需要做的就是使用模拟器关闭视图控制器,xcode 将为您编写测试。

不过,要回答您的问题,如果您想检查您的视图控制器是否被解雇,您可以编写一个断言来检查它是否是当前呈现的视图控制器,如下所示:

if var topController = UIApplication.shared.keyWindow?.rootViewController {
  while let presentedViewController = topController.presentedViewController {
    topController = presentedViewController
  }
XCTAssertTrue(!topController is AboutViewController)
}
于 2018-01-07T04:53:24.940 回答