iOS UITest之加载其他应用

UI测试:加载其他应用

打开其他应用

我们可以通过 XCUIApplication 类来初始化自己应用和其他应用(通过包名)

其他系统应用 bundleid 参考iOS 删除自带应用

XCUIDevice

XCUIDevice 可以模拟设备的具体操作,比如点击 home 键、音量键等

返回 Home

/// 点击 Home 键
func toHome() {
    
    
    XCUIDevice.shared.press(XCUIDevice.Button.home);
}

springboard 使用

可以通过com.apple.springboard来加载系统页面。从而进行模拟主界面操作。

let springboard = XCUIApplication.init(bundleIdentifier: "com.apple.springboard")
springboard.launch()

下拉打开通知

在页面中选取两个点,然后通过拖动模拟滑动显示通知(Objective-c 可以,而 Swift 不能操作)。

- (void)openNotification{
   	XCUIApplication *app = self.springboard;
    XCUICoordinate *coord1 = [app coordinateWithNormalizedOffset:CGVectorMake(0.1, 0.01)];
    XCUICoordinate *coord2 = [app coordinateWithNormalizedOffset:CGVectorMake(0.1, 0.8)];
    [coord1 pressForDuration:0.1 thenDragToCoordinate:coord2];
}

Safari 浏览器使用

可以通过com.apple.mobilesafari来加载浏览器,可以测试加载网页、通用链接唤醒应用、深链接唤醒应用等。

网页加载测试

定义加载方法

    /// 打开浏览器 访问地址
    /// - Parameter url: 访问地址 url
    /// - Returns: 浏览器实例,以便获取后续元素和延迟处理
    /// - Important: go 按钮点击后,进入异步操作,可能会耗时较久,建议后续元素操作设置较大(50-60)超时时间,以免超时崩溃
    func openSafariInput(url:String) -> XCUIApplication {
    
    
        let safari = XCUIApplication.init(bundleIdentifier: "com.apple.mobilesafari")
        safari.launch()
        // 确保唤醒应用
        XCTAssert(safari.wait(for: .runningForeground, timeout: 5), "应该唤起浏览器")
        
        // 开新 tab,防止其他影响
        safari.buttons["TabOverviewButton"].tap()
        safari.buttons["Close"].tap()
        
        // 输入地址
        let textfield = safari.textFields["Address"]
        textfield.tap()
        print("输入地址:\(url)")
        textfield.typeText(url)
        
        let goButton = safari.buttons["Go"]
        goButton.tap()
        sleep(1)
        return safari
    }

打开百度官网测试

    func testOpenBaidu() {
    
    
        let safari = openSafariInput(url: "https://www.baidu.com")
        let baidu = safari.otherElements["百度一下"] // 可以通过 safari.debugDescription 来查看元素进行验证
        XCTAssert(baidu.waitForExistence(timeout: 60), "应该加载百度主页") // 设置超长超时,避免没加载出页面导致测试异常
        //safari.terminate() // 关闭
    }

运行效果图如下:

Simulator Screen Recording - iPhone SE (2nd generation) - 2021-12-14 at 16.55.06

注意事项

  • 输入完地址后,请求是异步操作,可能会耗费较长时间,所以下一步操作应该将超时设置大一点。

  • 不同iOS版本浏览器样式可能不一样,搜索流程也可能不一样,所以需要根据打印元素层(xxx.debugDescription)来具体操作。

如何定位全局搜索?

我们可以通过滑动点到点触发搜索页面,但是通过打印 debugDescription 方法却没有 textfield 元素。

猜你喜欢

转载自blog.csdn.net/qq_14920635/article/details/121930916