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()方法