简体   繁体   中英

How to test a UILabel on a programatically added UIView with XCTest

I want to test the .text of my dashboardLabel , but i don't know how to access it via XCTest.

The DashboardView.swift looks like this:

import UIKit

class DashBoardView: UIView {

override init(frame: CGRect) {
    super.init(frame: frame)

    createSubviews()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    fatalError("init(coder:) has not been implemented")
}

// MARK: - Create Subviews

func createSubviews() {
    backgroundColor = .white

    var dashboardLabel : UILabel

    dashboardLabel = {
        let label = UILabel()
        label.text = "Dashboard Label"
        label.textColor = .black
        label.frame = CGRect(x:60, y:80, width: 200, height: 30)
        label.backgroundColor = .green
        label.backgroundColor = .lightGray
        label.font = UIFont(name: "Avenir-Oblique", size: 13)
        label.textAlignment = .center
        return label
    }()

}

The DashboardViewController.swift looks like this:

import UIKit

class DashBoardViewController: UIViewController {

    var dashboardview = DashBoardView()

    //MARK: View Cycle
    override func loadView() {
         view = dashboardview
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "DashBoard"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

I know how to test the Title of the DashboardViewController.swift

import XCTest
@testable import DashBoard

class DashBoardTests: XCTestCase {
    func test_if_title_is_DashBoard() {

    let vc = DashBoardViewController()
    let _ = vc.view
    XCTAssertEqual(vc.navigationItem.title, "Dashboard")
}

but i have absolutely no clue, how to access the dashboardLabel on the DashBoardView.swift .

I hope this explains my problem and anyone of you can help me, or point me in the right direction!

Thx ✌️

A fellow Software developer told me a solution which is pretty cool! You need to declare the Label as a property as follows

private(set) var dashboardLabel = UILabel()

and now you are able to access the property within the XCTest. Which makes sense, because you can only test things that are accessible from outside

import UIKit

class DashBoardView : UIView {

    private(set) var dashboardLabel = UILabel()

}

XCTest File

import XCTest
@testable import DashBoard

class DashBoardTests: XCTestCase {
    func test_if_dashboard_label_has_title_DashBoard() {

        let vc = DashBoardView()
        XCTAssertEqual(vc.dashboardLabel.text, "DashBoard")
    }
}

Hope that helps!

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