0

I am working on one issue where I need to change the Textfield's background color to the white color. I wanted to add the UI test case for it to check if background color of the XCUIElement(i.e Textfield) is white color or not. I searched for it but didn't not find any useful answer on it. I wanted to know if it is even possible check against background color in the UITest Cases.

I was going through Matt's answer, but didn't get clear idea.

https://stackoverflow.com/a/37754840/3278326

Thoughts?

Jarvis The Avenger
  • 2,750
  • 1
  • 19
  • 37

1 Answers1

1

Like guys replied in comments, we can't do it by UI tests, but I think we still have 2 ways to achieve this:

  1. Snapshot Tests:

     import SnapshotTesting
     ...
     func test_view_matchesSnapshot() {
         let view = makeYourView()
         assertSnapshot(matching: view, as: .wait(for: 1.5, on: .image))
     }
    
  2. Unit Tests:

     func test_view_shouldHaveTextFieldWithExpectedBackgroundColor() throws {
         let view = makeYourView()
    
         let textFieldBackgroundColor = try XCTUnwrap(
             view.textField.backgroundColor, 
             "textField.backgroundColor is nil"
         )
    
         let expectedTextFieldBackgroundColor = UIColor.white
    
         XCTAssertEqual(
             textFieldBackgroundColor.toHexString(),
             expectedTextFieldBackgroundColor.toHexString(),
             "textField doesn't have expected backgroundColor"
         )
     }
    

*Utility hex getters to compare two UIColors can be found here

**If your textField is private, then you can use this great solution and our unit test should look like this:

    func test_view_shouldHaveTextFieldWithExpectedBackgroundColor() throws {
        let view = makeYourView()

        let textField = try XCTUnwrap(
            YourViewMirror(reflecting: view).textField, 
            "Can't find textField property"
        )

        let textFieldBackgroundColor = try XCTUnwrap(
            textField.backgroundColor, 
            "textField.backgroundColor is nil"
        )

        let expectedTextFieldBackgroundColor = UIColor.white

        XCTAssertEqual(
            textFieldBackgroundColor.toHexString(),
            expectedTextFieldBackgroundColor.toHexString(),
            "textField doesn't have expected backgroundColor"
        )
    }

where

final class YourViewMirror: MirrorObject {
    init(reflecting yourView: YourView) {
        super.init(reflecting: yourView)
    }
    var textField: UITextField? {
        extract()
    }
}

and

class MirrorObject {
    let mirror: Mirror
    init(reflecting: Any) {
        self.mirror = Mirror(reflecting: reflecting)
    }

    func extract<T>(variableName: StaticString = #function) -> T? {
        return mirror.descendant("\(variableName)") as? T
    }
}
vsnv
  • 111
  • 3