使用DevEco Testing快速创建HarmonyOS5单元测试
1.测试环境准备
- 确保已安装DevEco Studio 5.0+
- 在module的build.gradle添加依赖:
dependencies {testImplementation 'org.junit.jupiter:junit-jupiter:5.8.2'ohosTestImplementation 'com.huawei.ohos.testkit:runner:1.0.0.200'
}
2.创建测试类(示例测试计算器功能)
import { describe, it, expect } from '@ohos/hypium'
import Calculator from '../src/main/ets/Calculator'describe('CalculatorTest', () => {it('testAdd_shouldReturn4_when2Plus2', () => {let calc = new Calculator()expect(calc.add(2, 2)).assertEqual(4)})it('testDivide_shouldThrowError_whenDivideByZero', () => {let calc = new Calculator()expect(() => calc.divide(5, 0)).toThrow()})
})
该测试用例包含正常运算和异常场景验证
3.配置测试运行器
<?xml version="1.0" encoding="UTF-8"?>
<configuration><target name="Phone" type="device"><parameter key="deviceType" value="phone"/></target><coverage enabled="true"/><timeout value="60000"/>
</configuration>
支持设备类型选择和代码覆盖率统计
4.执行测试(三种方式任选):
- 右键测试类选择"Run 'CalculatorTest'"
- 命令行执行:hdc shell aa test -b your.bundle.name
- 持续集成:配置TestKit到Jenkins流水线
5.查看测试报告:
测试完成后自动生成HTML报告,路径为:
/build/reports/tests/deviceTest/index.html
关键技巧:
- 使用@BeforeEach/@AfterEach处理测试前置/后置操作
- 通过@ParameterizedTest实现参数化测试
- 对UI组件使用@UiTest注解
- 模拟对象推荐使用ohos.mock()方法