Car*_*cia 3 xcode unit-testing ios swift
我想进行单元测试以查看视图控制器是否正在呈现另一个视图控制器。
func testMainTabController_WhenActionButtonIsTapped_NewSuppliersInvoiceControllerIsCreatedV2() {
let sut = MainTabBarController()
sut.loadViewIfNeeded()
let myExpectation = expectation(description: "The sut should present a view controller")
sut.actionButton.sendActions(for: .touchUpInside)
if let x = sut.presentedViewController {
myExpectation.fulfill()
} else {
XCTFail("The view controller was not presented")
}
wait(for: [myExpectation], timeout: 3)
}
Run Code Online (Sandbox Code Playgroud)
这里我得到的结果是测试失败。因为我得到 nil 作为presentedViewController。这是按钮的代码
@objc func handleActionButtonTap() {
let suppliersInvoiceController = SuppliersInvoiceController()
let navCon = UINavigationController(rootViewController: suppliersInvoiceController)
navCon.modalPresentationStyle = .fullScreen
present(navCon, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)
这是我在测试中写的代码。当我运行单元测试并调用当前方法时,按钮中的代码被成功调用。当然,如果我运行该应用程序,它就可以正常工作。当我点击按钮时,我会得到呈现的视图控制器。如果我在handleActionButtonTap()和print(vc)中输入let vc =presentedViewController,我就会得到nav con。但为什么我不能在单元测试中做到这一点?
有人知道发生了什么事吗?
谢谢
你想做的是做UITest而不是做UnitTest。
什么是单元测试? https://x-team.com/blog/how-to-get-started-with-ios-unit-tests-in-swift/
单元测试是您编写的用于测试有关您的应用程序的某些内容的函数。一个好的单元测试是小的。它只单独测试一件事。例如,如果您的应用程序将用户花在做某事上的总时间相加,您可以编写一个测试来检查该总数是否正确。
回到答案,为此进行 UI 测试。这是在谷歌搜索后进行 UI 测试的示例备忘单:https://github.com/joemasilotti/UI-Testing-Cheat-Sheet
在 UI 测试中,您将能够检查点击按钮或其他内容后屏幕是否被推送或呈现,例如:
XCTAssert(app.staticTexts["Some Static String From SuppliersInvoiceController "].exists)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2654 次 |
| 最近记录: |