Jack Of Diamonds Jack Of Diamonds - 4 months ago 16
Swift Question

Unit Test button added to view

I am a unit test newbie, I am testing if my button has been added to the view.

My first test passes correctly:

XCTAssertNotNil(vc.button, "button Not Initialised")


But my second test fails when i have the view.addSubview(button) in the code

XCTAssertNotNil(vc.button.superview, "button Not added to view")


My question is how do i test to see if the button has been added to the view, I am not using storyboards, everything is coded. Because the first test will pass regardless of if i have addSubview in the code or not.

Thanks

In my ViewController class i initialise the button:

private(set) lazy var myButton: UIButton = {
let myButton = UIButton(frame: CGRectZero)
return myButton
}()


and in viewDidLoad i add it to subview and give it constraints:

view.addSubview(myButton)


My test function is:

func testAddRoomButtonInRoomsViewController() {
let vc = myViewController()
XCTAssertNotNil(vc.myButton, "Button Not Initialised")
XCTAssertNotNil(vc.myButton.superview, "Button Not Added To View")
}

Answer

The viewDidLoad is not called in your test case, therefore it fails. You have to call it manually.

1. Introduce an extension

    extension UIViewController {

        func startViewLifecycle() {
            view.setNeedsLayout()
            view.layoutIfNeeded()
        }
    }

2. Call it in your test case:

func testAddRoomButtonInRoomsViewController() {
    let vc = myViewController()
    vc.startViewLifecycle()

    XCTAssertNotNil(vc.myButton, "Button Not Initialised")
    XCTAssertNotNil(vc.myButton.superview, "Button Not Added To View")
}