Use of undeclared type 'ViewController' when unit testing my own ViewController in Swift?

前端 未结 3 1517
谎友^
谎友^ 2020-12-29 21:06

I have been trying to write test cases in Swift to test my ViewController. However, when I try to instantiate my own ViewController in a XCTestCase I get \"Use of undecla

3条回答
  •  隐瞒了意图╮
    2020-12-29 21:54

    In swift 4 you can create a new unit test target, it should import the target you have selected as stated below

    In order to test any logic inside the view controller you should have a reference to it so that in order to reach the viewController you should has a reference to the storyboard first as stated below

    // Put setup code here. This method is called before the invocation of each test method in the class.
    let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
        viewController = storyBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
        _ = viewController.view
    

    The previous code should be inserted inside setUp method, this method is called each time the unit test is running. Note the viewController is a variable defined inside XCTestCase class as stated in the screenshot attached below

    For now you can access any logic defined inside the viewController class by calling viewController.funCode or viewController.variable

    enter image description here

    DO NOT FORGET: in order to reach the view controller by storyboard you should identify. in order to do that you should go to storyboard, then select the viewController, then from the right panel, go to "show the identity inspector" and set a value for the storyboard ID = 'ViewController'

    For more information please have a look at : https://github.com/msabukwaik/networking-example

提交回复
热议问题