如何在 UI 测试用例中检查 XCUIElement 的背景颜色?

问题描述

我正在解决一个问题,需要将文本字段的背景颜色更改为白色。我想为其添加 UI 测试用例,以检查 XCUIElement(即文本字段)的背景颜色是否为白色。我搜索了它,但没有找到任何有用的答案。我想知道是否可以检查 UITest Cases 中的背景颜色。

我正在阅读马特的回答,但没有得到明确的想法。

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

想法?

解决方法

就像评论中回复的那样,我们不能通过 UI 测试来做到这一点,但我认为我们仍然有 2 种方法可以做到这一点:

  1. Snapshot Tests

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

     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"
         )
     }
    

*可以找到用于比较两个 UIColors 的实用十六进制 getter here

**如果你的 textField 是私有的,那么你可以使用 this great solution 和我们的单元测试应该是这样的:

    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(),"textField doesn't have expected backgroundColor"
        )
    }

哪里

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

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
    }
}