Like guys replied in comments, we can't do it by UI tests, but I think we still have 2 ways to achieve this:
Snapshot Tests:
import SnapshotTesting
...
func test_view_matchesSnapshot() {
let view = makeYourView()
assertSnapshot(matching: view, as: .wait(for: 1.5, on: .image))
}
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
}
}