我如何从 XCUITest 检查 UISwitch 的 on/off 状态?

From an XCUITest how can I check the on/off state of a UISwitch?

我最近 运行 遇到这样一种情况,我需要能够从现有的存储桶中检查 UISwitch 的当前 on/off 状态(而不是它是否已启用以进行用户交互) XCUITests,而不是 XCTest,并将其切换到预定状态。我已将应用程序状态恢复添加到旧的现有应用程序,这现在干扰了预期 UISwitch 处于特定默认状态的运行之间的许多现有测试用例。

与 XCTest 不同,在 XCUITest 中您无法直接访问 UISwitch 状态。

在 Objective-C 中如何为 XCUITest 确定此状态?

我在这个博客 post 上很明显地找不到这个,因为 Swift 语言有类似的情况。 Xcode UITests: How to check if a UISwitch is on

根据这些信息,我测试并验证了两种解决问题的方法。

1) 判断状态是开还是关

XCUIElement *mySwitch = app.switches[@"My Switch Storyboard Accessibility Label"];
// cast .value to (NSString *) and test for @"0" if off state 
XCTAssertEqualObjects((NSString *)mySwitch.value, @"0", @"Switch should be off by default.");  // use @"1" to test for on state

2) 测试开关的状态是打开还是关闭然后切换它的状态

XCUIElement *mySwitch = app.switches[@"My Switch Storyboard Accessibility Label"];
// cast .value to (NSString *) and test for @"0" if off state 
if (![(NSString *)mySwitch.value isEqualToString:@"0"])
        [mySwitch tap];  // tap if off if it is on

使用方法 (2),我能够在测试用例运行之间强制所有 UISwitch 进入默认状态并避免状态恢复干扰。

Swift 5 版本:

XCTAssert((activationSwitch.value as? String) == "1")

或者您可以使用 XCUIElement 扩展名

import XCTest

extension XCUIElement {
    var isOn: Bool? {
        return (self.value as? String).map { [=11=] == "1" }
    }
}

// ...

XCTAssert(activationSwitch.isOn == true)

对于Swift

添加扩展 XCUIElement 断言直接切换 isOn 状态。

extension XCUIElement {
    
    func assert(isOn: Bool) {
        guard let intValue = value as? String else {
            return XCTAssert(false, "The value of element could not cast to String")
        }
        
        XCTAssertEqual(intValue, isOn ? "1" : "0")
    }
}

用法

yourSwitch.assert(isOn: true)

Swift 5: 不确定这是否对任何人都有用,但我刚刚开始使用 XCTest,并且根据@drshock 对这个问题的回复,我创建了一个简单的函数,我将其添加到我的 XCTestCase 中,该函数仅在关闭时打开开关。

    let app = XCUIApplication()

    func turnSwitchOnIfOff(id: String) {

        let myControl : NSString = app.switches.element(matching: .switch, identifier: id).value as! NSString

        if myControl == "0" {

            app.switches.element(matching: .switch, identifier: id).tap()

        }

    }

然后在我的测试中,当我想打开一个开关时,如果它是关闭的,我会使用它,其中 id 是来自开关辅助功能部分的标识符字符串。

    turnSwitchOnIfOff(id: "accessibilityIdentifierString")

定义

extension XCUIElement {
    var isOn: Bool {
        (value as? String) == "1"
    }
}

然后

XCAssertTrue(someSwitch.isOn)