我是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() {
}
}
答案 0 :(得分:0)
使用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)
}
答案 1 :(得分:0)
您可以创建一个模拟类,并覆盖原始类的所有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)
}