1

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 ✌️

sjm
  • 301
  • 2
  • 3
  • 10

2 Answers2

2

you can do that using accessibilityIdentifier

Refer : iOS XCUITests access element by accesibility

Gokul G
  • 698
  • 4
  • 11
0

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()

}

XCTestFile

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!

sjm
  • 301
  • 2
  • 3
  • 10