簡體   English   中英

單元測試,測試一個視圖 controller 是否已經呈現另一個視圖 controller

[英]Unit test, to test if a view controller has presented another view controller

我想進行單元測試以查看視圖 controller 是否呈現另一個視圖 controller。

   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)
    }

這里我得到的結果是失敗測試。 因為我作為presentedViewController得到了nil。 這是按鈕的代碼

@objc func handleActionButtonTap() {
    let suppliersInvoiceController = SuppliersInvoiceController()
    let navCon = UINavigationController(rootViewController: suppliersInvoiceController)
    navCon.modalPresentationStyle = .fullScreen
    present(navCon, animated: true, completion: nil)
}

這是我在測試中寫的代碼。 當我運行單元測試並調用當前方法時,按鈕中的代碼被成功調用。 當然,如果我運行該應用程序,它可以正常工作。 當我點擊按鈕時,我會看到呈現的視圖 controller。 如果我在 handleActionButtonTap() 和 print(vc) 中輸入 let vc = presentViewController,我會得到 nav con。 但是為什么我不能在單元測試中這樣做呢?

有人知道發生了什么嗎?

謝謝

你想要的是做UITest而不是UnitTest

什么是單元測試? https://x-team.com/blog/how-to-get-started-with-ios-unit-tests-in-swift/

單元測試是您編寫的 function,用於測試有關您的應用程序的某些內容。 一個好的單元測試很小。 它只單獨測試一件事。 例如,如果您的應用程序將用戶花費在某事上的總時間加起來,您可能會編寫一個測試來檢查這個總數是否正確。


所以回到答案,為此做 UI 測試。 這是在谷歌搜索后進行 UI 測試的示例備忘單: https://github.com/joemasilotti/UI-Testing-Cheat-Sheet

在 UI 測試中,您將能夠檢查在點擊按鈕或其他內容后是否按下或呈現屏幕,例如:

XCTAssert(app.staticTexts["Some Static String From SuppliersInvoiceController "].exists)

你 viewController 是否有足夠的上下文讓 presentViewController:animated: 工作? 例如,它沒有 window。 PresentViewController:animated: 在“水平規則環境”等中做不同的事情。

如果您想進行單元測試,如何將 VC 更改為不直接從其自身呈現其他 VC,而是讓它調用一個方法,例如您可以模擬的協調器 object,然后斷言模擬版本的 'present:animated: ' 如你所料被調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM