Search code examples
iosswifttdd

how to test methods which set private variables in viewcontroller unit testing?


I have a ViewController, which conforms to a protocol. ViewController has the following private UI components: backgroundImage, logoimage, loginButton , signupButton - all of these are private. (hence not accessible by unit tests)

How can I test the below protocol method implementation in unit testing? I am using XCTestFramework for unit testing.

extension ViewController : ViewControllerProtocol{
    func setbackgroundImage(_ image: UIImage) {
        backgroundImage.image = image
    }

    func setLogoImage(_ image: UIImage) {
        logoImage.image = image
    }

    func setLoginButtontitle(_ title: String) {
        loginButton.setTitle(title, for: .normal)
    }

    func setSignupButtonTitle(_ title: String) {
        signupButton.setTitle(title, for: .normal)
    }
}

protocol ViewControllerProtocol {
    func setbackgroundImage(_ image : UIImage)
    func setLogoImage(_ image : UIImage)
    func setLoginButtontitle(_ title: String)
    func setSignupButtonTitle(_ title: String)
    func setTitleLabel(_ title: String)
    func setContinuewithoutsignupTitle(_ title: String)
}


Solution

  • You can still unit test those values below by adding public getters

    
    protocol ViewControllerProtocol {
        func setbackgroundImage(_ image : UIImage)
        func setLogoImage(_ image : UIImage)
        func setLoginButtontitle(_ title: String)
        func setSignupButtonTitle(_ title: String)
        func setTitleLabel(_ title: String)
        func setContinuewithoutsignupTitle(_ title: String)
        func getbackgroundImage() -> UIImage?
        func getlogoImage() -> UIImage?
        func getloginButtonTitle() -> String?
        func getsignupButtonTitle() -> String?
    }
    
    class MainTest: XCTestCase {
    
        let viewController = ViewController()
    
        override func setUp() {
            super.setUp()
        }
    
        func testExample() {
            guard let testImage1 = UIImage(named: "testImage1") else {
                XCTFail("Could not load test image 1")
                return
            }
            viewController.setbackgroundImage(testImage1)
            XCTAssert(viewController.getbackgroundImage() == testImage1)
            guard let testImage2 = UIImage(named: "testImage2") else {
                XCTFail("Could not load test image 2")
                return
            }
            viewController.setLogoImage(testImage2)
            XCTAssert(viewController.getlogoImage() == testImage2)
            viewController.setLoginButtontitle("test")
            XCTAssert(viewController.getloginButtonTitle() == "test")
            viewController.setSignupButtonTitle("test")
            XCTAssert(viewController.getsignupButtonTitle() == "test")
        }
    
    }