简体   繁体   English

Swift单元测试-等待viewDidLoad

[英]Swift Unit Test- Wait for viewDidLoad

I am new to Unit test in Swift. 我是Swift中的单元测试新手。 Now I wanted to test my viewController. 现在,我想测试我的viewController。 In viewDidLoad I have an asynchronous call. 在viewDidLoad中,我有一个异步调用。 So that if I want to test my Controller if the data got loaded correctly, the data didn't got loaded. 因此,如果我要测试控制器是否正确加载了数据,则数据没有加载。 I already read that I have to build in an XCTestExpectation. 我已经读过我必须建立在XCTestExpectation中。

So the information I have, I got from this question: XCTest Unit Test data response not set in test after viewDidLoad 所以我从这个问题中得到了信息: viewDidLoad之后,未在测试中设置XCTest单元测试数据响应

The answer there is an example from which I don't know how to implement. 答案有一个我不知道如何实现的示例。 My test class looks like this: 我的测试课看起来像这样:

import XCTest
@testable import apirequest

class SearchedForViewControllerTests: XCTestCase {
    var vc: SearchedForViewController!

    override func setUp() {
        super.setUp()

        let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        vc = storyboard.instantiateViewController(withIdentifier: "SearchedForViewController") as! SearchedForViewController

        vc.passedString = "garten"
        let _ = vc.view
    }

    func testArticlesShwon() {
        print(vc.tableView.numberOfRows(inSection: 0))
    }    
}

So if I look on my own code the part of viewDidLoad happens in 因此,如果我查看自己的代码,则viewDidLoad的一部分发生在

let _ = vc.view

If I want to build in a Expectation, I have to wait for this part. 如果我想建立一个Expectation,则必须等待这一部分。 But the part is not a function. 但是该部分不是功能。 So I don't know how I could tell my Expectation to fulfill after loading. 所以我不知道如何告诉我的期望在加载后实现。

This may be more of an opinion/design answer, but I would highly recommend testing your ViewController and your Model completely separately. 这可能更多是一个意见/设计答案,但我强烈建议您完全分别测试ViewController和Model。

Eg when you're testing your VC, manually set the data in your tests, then separately have tests to ensure your model and any networking/async calls are functioning properly. 例如,当您测试VC时,请在测试中手动设置数据,然后单独进行测试以确保模型和所有联网/异步调用均正常运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM