在测试场景中,调用部分接口无法获取到有效的返回值,这样开发者在测试时无法覆盖查询不同返回值的场景,此时,可以使用mock功能。当前Instrument Test和Local Test均支持mock能力,有两种实现方式,一是使用hamock或者hypium插件包的mock接口,二是使用import mock。
说明
仅API 11及以上版本的Stage工程支持。
使用hamock/hypium插件包的mock接口
以下例子通过mock接口模拟类的某个方法。
- 在src/main/ets目录下新建一个ArkTS文件,例如ClassForMock.ets,并在其中导出一个类。
export class ClassForMock {
constructor() {
}
method_1(arg: string) {
return '888888';
}
method_2(arg: string) {
return '999999';
}
}
- 在测试文件中编写如下代码。
import { describe, expect, it, MockKit, when } from '@ohos/hypium';
import { ClassForMock } from '../../../main/ets/ClassForMock';
export default function afterReturnTest() {
describe('afterReturnTest', () => {
it('afterReturnTest', 0, () => {
console.info("it begin");
// 1.创建一个mock能力的对象MockKit
let mocker: MockKit = new MockKit();
// 2.定义类ClassForMock,里面两个函数,然后创建一个对象classForMock
let classForMock: ClassForMock = new ClassForMock();
// 3.进行mock操作,比如需要对ClassName类的method_1函数进行mock
let mockFunc: Function = mocker.mockFunc(classForMock, classForMock.method_1);
// 4.期望classForMock.method_1函数被mock后, 以'test'为入参时调用函数返回结果'1'
when(mockFunc)('test').afterReturn('1');
// 5.对mock后的函数进行断言,看是否符合预期
// 执行成功案例,参数为'test'
expect(classForMock.method_1('test')).assertEqual('1'); // 执行通过
})
})
}
- 执行测试,用例通过。
使用import mock
在mock-config.json5配置文件中定义目标module和mock文件的映射关系,运行时import目标module都将指向mock实现代码。以系统API bluetoothManager为例,具体实现如下。
- 在src/mock目录下新建一个ArkTS文件,例如bluetooth_manager.mock.ets,在这个文件内定义目标Module的Mock实现。
enum BluetoothState {
/** Indicates the local Bluetooth is off */
STATE_OFF = 0,
/** Indicates the local Bluetooth is turning on */
STATE_TURNING_ON = 1,
/** Indicates the local Bluetooth is on, and ready for use */
STATE_ON = 2,
/** Indicates the local Bluetooth is turning off */
STATE_TURNING_OFF = 3,
/** Indicates the local Bluetooth is turning LE mode on */
STATE_BLE_TURNING_ON = 4,
/** Indicates the local Bluetooth is in LE only mode */
STATE_BLE_ON = 5,
/** Indicates the local Bluetooth is turning off LE only mode */
STATE_BLE_TURNING_OFF = 6
}
interface BluetoothInfo {
state: number
}
const MockBluetoothManager: Record<string, Object> = {
'getBluetoothInfo': () => {
return { state : BluetoothState.STATE_BLE_TURNING_ON } as BluetoothInfo;
},
};
export default MockBluetoothManager;
- 在Mock配置文件src/mock/mock-config.json5中定义目标Module与Mock实现的映射关系。
"@ohos.enterprise.bluetoothManager": { // 待替换的moduleName
"source": "src/mock/bluetooth_manager.mock.ets" // mock代码的路径,相对于模块根目录
}
- 在测试文件中编写如下代码。
import { describe, it, expect } from '@ohos/hypium';
import { bluetoothManager } from '@kit.MDMKit';
export default function mock_system_api() {
describe('mock_system_api', () => {
/* mock系统API */
it('mock_system_api', 0, () => {
let bluetoothInfo = bluetoothManager.getBluetoothInfo({
bundleName: "com.example.myapplication"
})
expect(bluetoothInfo.state).assertEqual(4)
});
});
}
- 执行测试,用例通过。