【关键词】
单元测试框架、HarmonyOS Test、assertThrowError、assertFail、assertEqual
【测试代码及测试结果展示】
这里以新建API9工程自动生成的ohosTest来编写单元测试代码。
1、 测试代码:
- import { describe, it, expect } from '@ohos/hypium'
- import abilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry';
-
- class CharacterReader {
- constructor() {
- }
- unconsume(){
- throw new Error("this is an error")
- }
- unconsume1(a: number,b: number){
- if (a == 1 && b == 2) {
- throw new Error("this is an error")
- }
- }
- add(a: number,b: number) {
- return a + b
- }
- }
-
- export default function abilityTest() {
- describe('ActsAbilityTest', function () {
- // 验证待验证方法的行为时,不带括号
- it('assertThrowError',0,() => {
- let reader = new CharacterReader()
- expect(reader.unconsume).assertThrowError("this is an error")
- })
- // expect验证行为不能带括号,目前想要传递参数就另行封装一个空参方法,再转而测试这个空参方法,如下
- it('assertThrowError', 0, () => {
- let reader = new CharacterReader();
- let a = 1;
- let b = 2;
- const test:Function = () => {
- reader.unconsume1(a,b)
- }
- expect(test).assertThrowError("this is an error")
- })
-
- // 验证待验证方法的行为时,带括号
- it('assertEqual',0,() => {
- let reader = new CharacterReader()
- expect(reader.add(1,1)).assertEqual(2)
- })
-
- // assertFail断言,使一个用例强制失败
- it('assertFail',0,() => {
- let reader = new CharacterReader()
- expect(reader.unconsume).assertFail()
- })
- })
- }
2、 测试结果
【参考文档】
1、https://developer.harmonyos.com/cn/docs/documentation/doc-guides/harmonyos_jnit_jsunit-0000001092459608
2、https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/unit-test-0000001507402510-V3#section160718461418