【问题标题】:How can I UITest the change of the image of a UIButton in Swift?如何在 Swift 中 UITest 更改 UIButton 的图像?
【发布时间】:2018-07-28 19:47:06
【问题描述】:

当我点击UIButton 时,图像应该会改变以反映其新状态(例如记录 -> 暂停等)。

在我的 XCode UITest 函数中,如何在点击后询问按钮当前图像以断言其图像已正确更改为正确图像的 .png 文件?

【问题讨论】:

  • 相关——似乎不能直接:stackoverflow.com/a/31251379/3151675
  • 这在 XCTest UI 测试中是不可能的。您需要对分配的图像进行单元测试,因为 UI 测试是功能性的,而不是视觉的。

标签: swift uibutton xcode-ui-testing


【解决方案1】:

我是这样做的

// Find the button by the image name
// In this example the image's names are "record_image" and "pause_image"
// "_" are replaced by " " in the image name when searching
let recordButton = XCUIApplication().buttons["record image"]
recordButton.tap()
XCTAssertFalse(recordButton.exists) // Record button won't exist anymore since the image has changed
let pauseButton = XCUIApplication().buttons["pause image"]
XCTAssertTrue(pauseButton.exists)
pauseButton.tap()
XCTAssertFalse(pauseButton.exists)
XCTAssertTrue(recordButton.exists)

【讨论】:

    【解决方案2】:

    我确实喜欢这样,不是最好的方法,但对我来说很有效,

    每次图像更改我都会更改可访问性标识符,然后检查 access.ids

    public func setFollowed(_ isFollowed: Bool) {
        if isFollowed {
            followButton.setImage(UIImage(named: "followed-green-icon"), for: .normal)
            followButton.accessibilityIdentifier = "ProfileInfoView_followButton_followed"
        }
        else {
            followButton.setImage(UIImage(named: "follow-blue-icon"), for: .normal)
            followButton.accessibilityIdentifier = "ProfileInfoView_followButton_follow"
        }
    }
    

    示例 UI 测试部分:

    func getFollowButton(isFollowed: Bool) -> XCUIElement {
        if isFollowed == true {
            return app.descendants(matching: .button)["ProfileInfoView_followButton_followed"]
        } else {
            return app.descendants(matching: .button)["ProfileInfoView_followButton_follow"]
        }
    }
    

    然后测试返回的元素,状态改变等。

    【讨论】:

      猜你喜欢
      • 2015-01-06
      • 2015-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      相关资源
      最近更新 更多