简体   繁体   中英

Swift Unit Test- Wait for viewDidLoad

I am new to Unit test in Swift. Now I wanted to test my viewController. In viewDidLoad I have an asynchronous call. 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.

So the information I have, I got from this question: XCTest Unit Test data response not set in test after viewDidLoad

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

let _ = vc.view

If I want to build in a Expectation, I have to wait for this part. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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