【问题标题】:How to check background color of the XCUIElement in UI test cases?? [closed]如何在 UI 测试用例中检查 XCUIElement 的背景颜色? [关闭]
【发布时间】:2021-04-11 20:48:01
【问题描述】:

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

我正在阅读马特的回答,但没有弄清楚。

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

想法?

【问题讨论】:

  • 不,这是不可能的,原因与 matt 解释的相同 - 基础标签及其属性未在 XCUIElement 中公开。
  • @Pranav 还有其他方法可以实现吗?
  • 单元测试或快照测试
  • 但是单元测试是为了功能测试,对吧?
  • 如果可能,能否提供快照测试的例子?

标签: ios swift xctest ui-testing xcuitest


【解决方案1】:

就像在 cmets 中回答的人一样,我们无法通过 UI 测试来做到这一点,但我认为我们仍然有两种方法可以实现这一点:

  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 的实用 hex 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(),
            expectedTextFieldBackgroundColor.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
    }
}

【讨论】:

    猜你喜欢
    • 2016-12-04
    • 2020-02-27
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    相关资源
    最近更新 更多