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

为君一笑 提交于 2020-01-03 16:58:58

问题


I recently ran into a situation where I needed to be able to check the current on/off state (NOT whether it is enabled for user interaction) of a UISwitch from within an existing bucket of XCUITests, not an XCTest, and toggle it to a pre-determined state. I had added app state restoration to an old existing app and this is now interfering with a number of existing testcases between runs that expected the UISwitches in particular default states.

Unlike XCTest, within XCUITest you do not have access to the UISwitch state directly.

How is this state determined in Objective-C for an XCUITest?


回答1:


Failing to find this anywhere obvious I happened upon this blog post for a similar situation for the Swift language. Xcode UITests: How to check if a UISwitch is on

With this information I tested and verified two approaches to solve my problem.

1) To assert if the state is on or off

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) To test if the state of the switch is on or off then toggle its state

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

Using approach (2), I was able to force a default state for all UISwitches in between testcase runs and avoid the state restoration interference.




回答2:


Swift 5 version:

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

Alternatively you can have a XCUIElement extension

import XCTest

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

// ...

XCTAssert(activationSwitch.isOn == true)



来源:https://stackoverflow.com/questions/44222966/from-an-xcuitest-how-can-i-check-the-on-off-state-of-a-uiswitch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!