鸿蒙5设备兼容性测试:AGC云真机服务初体验

一、AGC云真机服务介绍

  1. 什么是AGC云真机服务
    AGC(AppGallery Connect)云真机服务是华为提供的在线设备测试平台,开发者可以通过浏览器远程访问真实HarmonyOS设备,进行应用测试和兼容性验证。

  2. 云真机服务核心功能
    ​​远程真机调试​​:实时操作云端真实设备
    ​​多设备并行测试​​:同时测试多款设备
    ​​自动化测试​​:支持录制回放和自动化脚本
    ​​性能分析​​:CPU、内存、网络等指标监控
    ​​兼容性报告​​:自动生成测试报告
    二、环境准备与配置

  3. 开通云真机服务
    登录AppGallery Connect
    进入你的项目
    选择"质量" > "云真机服务"
    点击"立即开通"按钮

  4. 配置HarmonyOS测试应用
    在entry/build.gradle中添加测试依赖:

dependencies {
// 测试框架
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'

// UI测试
implementation 'ohos.uitest:runner:1.0.0'
implementation 'ohos.uitest:junit4:1.0.0'
implementation 'ohos.uitest:core:1.0.0'

}
三、创建兼容性测试任务

  1. 准备测试脚本示例
    创建entry/src/test/ets/compatibility/DeviceCompatibilityTest.ets:

import { describe, it, expect, TestRunner } from 'deccjsunit';
import { Driver, ON, UiComponent } from 'ohos.uitest';

@Entry
@Component
struct DeviceCompatibilityTest {
@State message: string = '正在运行兼容性测试...';

build() {
    Column() {
        Text(this.message)
            .fontSize(20)
            .margin(10)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
}

async onPageShow() {
    await this.runCompatibilityTests();
}

async runCompatibilityTests() {
    try {
        // 初始化测试驱动
        const driver = await Driver.create();
        
        // 开始测试套件
        describe('DeviceCompatibilityTest', function() {
            // 测试案例1:检查屏幕分辨率兼容性
            it('testScreenResolution', 0, async function() {
                const display = await driver.getDisplay();
                console.log(`设备分辨率: ${display.width}x${display.height}`);
                
                // 验证应用在不同分辨率下的布局
                const rootComponent = await driver.findComponent(ON.id('rootLayout'));
                const bounds = await rootComponent.getBounds();
                
                expect(bounds.width).toBeGreaterThan(0);
                expect(bounds.height).toBeGreaterThan(0);
                this.message = '屏幕分辨率测试通过';
            });

            // 测试案例2:检查API兼容性
            it('testSystemAPIs', 0, async function() {
                // 验证设备支持的API级别
                const systemInfo = await driver.getSystemInfo();
                console.log(`HarmonyOS版本: ${systemInfo.osVersion}`);
                
                expect(systemInfo.apiLevel).toBeGreaterThanOrEqual(5);
                this.message = '系统API测试通过';
            });

            // 测试案例3:UI组件兼容性测试
            it('testUIComponents', 0, async function() {
                // 测试文本组件
                const textComp = await driver.findComponent(ON.textContains('运行'));
                expect(await textComp.getText()).toContain('运行');
                
                // 测试按钮点击
                const button = await driver.findComponent(ON.type('Button'));
                await button.click();
                
                this.message = 'UI组件测试通过';
            });
        });
        
        // 运行测试
        await new TestRunner().run();
        this.message = '所有兼容性测试通过';
    } catch (error) {
        console.error('兼容性测试失败:', error);
        this.message = '测试失败: ' + error.message;
    }
}

}
四、在AGC云真机上运行测试

  1. 上传测试包
    在DevEco Studio中构建测试HAP:
    ./gradlew assembleDebug
    在entry/build/default/outputs/default/目录找到测试HAP文件
    在AGC控制台"云真机服务"页面点击"上传应用"
    选择构建的HAP文件
  2. 创建测试任务
    进入"测试任务"页面
    点击"新建任务"
    配置任务参数:
    {
    "taskName": "HarmonyOS5兼容性测试",
    "appFile": "你的应用HAP",
    "testType": "COMPATIBILITY",
    "deviceList": [
    "HUAWEI Mate 60 Pro",
    "HUAWEI P50 Pro",
    "HONOR Magic5 Pro"
    ],
    "testScript": "自动生成", // 或上传自定义脚本
    "timeout": 1800
    }
  3. 监控测试进度
    通过AGC控制台实时查看:

设备分配状态
测试执行进度
实时日志输出
性能指标监控
五、自动化测试脚本开发

  1. 录制测试脚本
    在云真机界面点击"录制脚本"
    手动操作设备完成测试流程
    保存生成的测试脚本
  2. 编写高级测试脚本
    创建entry/src/test/ets/automation/LoginTest.ets:

import { Driver, ON, UiComponent } from 'ohos.uitest';

export async function loginTest(driver: Driver) {
// 启动应用
await driver.delay(2000);

// 输入用户名
const usernameInput = await driver.findComponent(ON.id('username_input'));
await usernameInput.setText('testuser');

// 输入密码
const passwordInput = await driver.findComponent(ON.id('password_input'));
await passwordInput.setText('Test@1234');

// 点击登录按钮
const loginButton = await driver.findComponent(ON.id('login_button'));
await loginButton.click();

// 验证登录结果
await driver.assertComponentExist(ON.text('登录成功'));

// 截图保存
await driver.screenshot('login_success.png');

}
3. 集成到测试任务
在云真机测试配置中上传自定义脚本:

{
"testScript": {
"type": "CUSTOM",
"files": ["LoginTest.ets"],
"entry": "loginTest"
}
}
六、测试结果分析与报告

  1. 获取测试报告
    测试完成后,在AGC控制台可以:

查看详细的兼容性报告
下载日志和截图
分析性能数据
2. 解析测试结果代码示例
创建报告分析工具ReportAnalyzer.ets:

import http from '@ohos.net.http';

export class ReportAnalyzer {
private static readonly AGC_API = 'https://console.cloud.huawei.com/apitest';

// 获取测试报告
static async getTestReport(taskId: string): Promise<any> {
    const httpRequest = http.createHttp();
    
    try {
        const response = await httpRequest.request(
            `${this.AGC_API}/report/v1/test/${taskId}`,
            {
                method: 'GET',
                header: {
                    'Content-Type': 'application/json'
                }
            }
        );
        
        return JSON.parse(response.result);
    } catch (error) {
        console.error('获取测试报告失败:', error);
        throw error;
    }
}

// 分析兼容性问题
static analyzeCompatibility(report: any) {
    const results = {
        passed: 0,
        failed: 0,
        devices: {} as Record<string, any>
    };
    
    report.devices.forEach((device: any) => {
        const deviceResult = {
            model: device.model,
            osVersion: device.osVersion,
            passed: 0,
            failed: 0,
            issues: [] as string[]
        };
        
        device.testCases.forEach((testCase: any) => {
            if (testCase.status === 'PASSED') {
                results.passed++;
                deviceResult.passed++;
            } else {
                results.failed++;
                deviceResult.failed++;
                deviceResult.issues.push(
                    `${testCase.name}: ${testCase.errorMessage || '未知错误'}`
                );
            }
        });
        
        results.devices[device.model] = deviceResult;
    });
    
    return results;
}

// 生成Markdown格式报告
static generateMarkdownReport(analysis: any): string {
    let report = `# 兼容性测试报告\n\n`;
    report += `**通过率**: ${((analysis.passed / (analysis.passed + analysis.failed)) * 100).toFixed(2)}%\n\n`;
    report += `**通过**: ${analysis.passed}  **失败**: ${analysis.failed}\n\n`;
    
    report += `## 设备详情\n`;
    for (const [model, device] of Object.entries(analysis.devices)) {
        report += `### ${model}\n`;
        report += `- 系统版本: ${device.osVersion}\n`;
        report += `- 通过: ${device.passed} 失败: ${device.failed}\n`;
        
        if (device.issues.length > 0) {
            report += `#### 问题列表\n`;
            device.issues.forEach(issue => {
                report += `- ${issue}\n`;
            });
        }
        report += '\n';
    }
    
    return report;
}

}
七、常见问题解决方案

  1. 设备连接失败
    ​​解决方案:​​

检查网络连接
确认设备未被占用
重新初始化设备
​​代码检查:​​

async function checkDeviceConnection(deviceId: string): Promise {
try {
const driver = await Driver.create({ deviceId });
const info = await driver.getDeviceInfo();
return !!info;
} catch (error) {
console.error(设备${deviceId}连接失败:, error);
return false;
}
}
2. 测试超时处理
​​优化方案:​​

async function runWithTimeout(testFunc: Function, timeout: number) {
return new Promise(async (resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(测试超时 (${timeout}ms)));
}, timeout);

    try {
        await testFunc();
        clearTimeout(timer);
        resolve(true);
    } catch (error) {
        clearTimeout(timer);
        reject(error);
    }
});

}

// 使用示例
await runWithTimeout(() => loginTest(driver), 30000);
3. 多设备并行测试
​​实现方案:​​

import taskpool from '@ohos.taskpool';

async function runParallelTests(devices: string[], testScript: string) {
const tasks = devices.map(deviceId => {
return taskpool.execute(async () => {
try {
const driver = await Driver.create({ deviceId });
// 动态导入测试脚本
const testModule = await import(testScript);
await testModule.default(driver);
return { deviceId, status: 'PASSED' };
} catch (error) {
return { deviceId, status: 'FAILED', error: error.message };
}
});
});

return await Promise.all(tasks);

}

// 使用示例
const results = await runParallelTests(
['device1', 'device2', 'device3'],
'./ets/automation/LoginTest.ets'
);
八、实战案例:电商应用兼容性测试

  1. 测试场景设计
    ​​首页加载测试​​:验证不同设备上的布局兼容性
    ​​商品详情页测试​​:检查图片和文字显示
    ​​购物车功能测试​​:验证交互一致性
    ​​支付流程测试​​:确保关键流程可用
  2. 完整测试脚本
    创建entry/src/test/ets/ecommerce/EcommerceTest.ets:

import { Driver, ON, UiComponent } from 'ohos.uitest';

export async function ecommerceCompatibilityTest(driver: Driver) {
// 1. 首页测试
await testHomePage(driver);

// 2. 商品搜索测试
await testProductSearch(driver);

// 3. 购物车测试
await testShoppingCart(driver);

// 4. 支付流程测试
await testPaymentFlow(driver);

}

async function testHomePage(driver: Driver) {
// 验证首页banner
const banner = await driver.findComponent(ON.id('home_banner'));
expect(await banner.isDisplayed()).toBeTruthy();

// 验证分类菜单
const categories = await driver.findComponents(ON.type('CategoryItem'));
expect(categories.length).toBeGreaterThan(3);

// 滑动测试
await driver.swipe(0.5, 0.8, 0.5, 0.2, 500);

}

async function testProductSearch(driver: Driver) {
// 点击搜索框
const searchBox = await driver.findComponent(ON.id('search_input'));
await searchBox.click();

// 输入搜索词
await driver.delay(500);
await driver.enterText('智能手机');

// 点击搜索按钮
const searchBtn = await driver.findComponent(ON.id('search_button'));
await searchBtn.click();

// 验证搜索结果
await driver.delay(2000);
const products = await driver.findComponents(ON.type('ProductItem'));
expect(products.length).toBeGreaterThan(0);

}

async function testShoppingCart(driver: Driver) {
// 进入第一个商品
const firstProduct = await driver.findComponent(ON.index(0).type('ProductItem'));
await firstProduct.click();

// 添加到购物车
const addToCartBtn = await driver.findComponent(ON.id('add_to_cart'));
await addToCartBtn.click();

// 验证购物车数量
const cartBadge = await driver.findComponent(ON.id('cart_badge'));
expect(await cartBadge.getText()).toBe('1');

}

async function testPaymentFlow(driver: Driver) {
// 进入购物车
const cartIcon = await driver.findComponent(ON.id('cart_icon'));
await cartIcon.click();

// 点击结算
const checkoutBtn = await driver.findComponent(ON.id('checkout_button'));
await checkoutBtn.click();

// 选择支付方式
const paymentMethod = await driver.findComponent(ON.text('华为支付'));
await paymentMethod.click();

// 验证支付页面
const paymentTitle = await driver.findComponent(ON.id('payment_title'));
expect(await paymentTitle.getText()).toContain('支付');

}
3. 在AGC云真机上运行
上传电商应用HAP
创建测试任务选择"EcommerceTest.ets"
选择10款不同设备
启动并行测试
总结
通过本文的学习,你已经掌握了使用AGC云真机服务进行HarmonyOS 5应用兼容性测试的完整流程:

​​环境准备​​:开通服务并配置测试环境
​​测试开发​​:编写兼容性测试脚本和自动化测试
​​任务执行​​:在云端真机上运行测试
​​结果分析​​:解析测试报告并发现问题
​​实战应用​​:电商应用全流程测试案例
AGC云真机服务为HarmonyOS开发者提供了强大的测试能力,帮助开发者:

节省设备采购成本
提高测试覆盖率
快速发现兼容性问题
确保应用质量
随着测试需求的增加,你可以进一步探索:

更复杂的自动化测试场景
与CI/CD流水线集成
性能基准测试
长时间稳定性测试

posted @ 2025-06-28 22:42  暗雨YA  阅读(205)  评论(0)    收藏  举报