目录

Mock

In real-world development, some APIs or objects depend on external resources or complex logic, which can be tricky to set up in a test environment, making them difficult to test. In such cases, you can use mock capabilities to simulate these APIs or objects. Currently, both instrument and local tests support module mocking. For system module APIs or external dependency modules, use import mock to simulate them. For local modules, use the mock APIs provided by the hamock or hypium plugin package, or also use import mock.

This feature is available only for projects developed using API version 11 or later based on the stage model.

Mocking System Modules or External Dependency Modules

You can mock system module APIs or methods of dependency modules using import mock. In the mock-config.json5 configuration file, define a mapping between the target module and the mock implementation file. At runtime, all imports of the target module will redirect to the mock implementation. The following uses the system API bluetoothManager as an example to describe the implementation.

  1. In the src/mock directory, create an ArkTS test file, for example, bluetooth_manager.mock.ets, and define the mock implementation of the target module in this file.
    // src/mock/bluetooth_manager.mock.ets
    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;
  2. In the src/mock/mock-config.json5 file, define the mapping between the target module and mock implementation file.
    "@ohos.enterprise.bluetoothManager": {  // Name of the module to be replaced.
      "source": "src/mock/bluetooth_manager.mock.ets"  // Path to the mock implementation code, relative to the root directory of the module.
    }
  3. Write the following code in the test file:
    // bluetoothManager.test.ets
    import { describe, it, expect } from '@ohos/hypium';
    import { bluetoothManager } from '@kit.MDMKit';
    
    export default function mock_system_api() {   
      describe('mock_system_api', () => {
        /* Mock the system API. */
        it('mock_system_api', 0, () => {
          let bluetoothInfo = bluetoothManager.getBluetoothInfo({
            bundleName: "com.example.myapplication"
          })
          expect(bluetoothInfo.state).assertEqual(4)
        });
      });
    }
  4. If the test file is manually created, add the test case class mock_system_api to the List.test.ets file.
    import mock_system_api from './bluetoothManager.test';
    
    export default function testsuite() {
      mock_system_api();
    }
  5. Perform the test. The test case should be passed.

Mocking Local Modules

You can mock local modules using the mock APIs provided by the hamock or hypium plugin package or using import mock.

[h2]Using the mock APIs in the hamock or hypium Plugin Package

The following example demonstrates how to use the mock APIs to mock a specific method in a local module. For details, see Mock.

  1. Create an ArkTS test file, for example, ClassForMock.ets, under src/main/ets, and export a class from the file.
    export class ClassForMock {
      constructor() {
      }
      method_1(arg: string) {
        return '888888';
      }
      method_2(arg: string) {
        return '999999';
      }
    }
  2. Write the following code in the test file:
    // afterReturnTest.test.ets
    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. Create a MockKit object.
          let mocker: MockKit = new MockKit();
          // 2. Define the ClassForMock class, which contains two functions, and then create a classForMock object.
          let classForMock: ClassForMock = new ClassForMock();
          // 3. Mock method_1 of the ClassForMock class.
          let mockFunc: Function = mocker.mockFunc(classForMock, classForMock.method_1);
          // 4. It is expected that, after the classForMock.method_1 function is mocked, the result '1' is returned when the function is called with 'test' passed in.
          when(mockFunc)('test').afterReturn('1');
          // 5. Assert whether the mocked function is implemented as expected.
          // The operation is successful if 'test' is passed in.
          expect(classForMock.method_1('test')).assertEqual('1'); // The operation is successful.
        })
      })
    }
  3. If the test file is manually created, add the test case class afterReturnTest to the List.test.ets file.
    import afterReturnTest from './afterReturnTest.test';
    
    export default function testsuite() {
      afterReturnTest();
    }
  4. Perform the test. The test case should be passed.

[h2]Using import mock

You can mock local modules using import mock, following a process similar to mocking system or external dependency modules: In the mock-config.json5 configuration file, define a mapping between the target module and the mock implementation file. At runtime, all imports of the target module will redirect to the mock implementation. The following example demonstrates how to mock the sum function from a local module located at entry/src/main/ets/common/calc.ets.

  1. In the src/mock directory, create a common directory and an ArkTS test file, for example, calc.mock.ets, and define the mock implementation of the target module in this file.
    // src/mock/common/calc.mock.ets
    export function sum() {
      return "this is mock sum";
    }

    Original implementation of calc.ets:

    // src/main/ets/common/calc.ets
    export function sum() {
      return 1;
    }
  2. In the src/mock/mock-config.json5 file, define the mapping between the target module and mock implementation file.
    {
      "common/calc.ets": { // Specify the path of the file relative to the ets directory, including the file name extension.
        "source": "src/mock/common/calc.mock.ets"  // Path to the mock implementation code, relative to the root directory of the module.
      },
    }
  3. Write the following code in the test file:
    // test_mock_local_method.test.ets
    import { describe, it, expect } from '@ohos/hypium'
    import { sum } from '../../../main/ets/common/calc';
    
    export default function test_mock_local_method() {
      describe('test_mock_local_method', () => {
        it("test_mock_local_method", 0, () => {
          expect(sum()).assertEqual("this is mock sum")
        })
      })
    }
  4. If the test file is manually created, add the test case class test_mock_local_method to the List.test.ets file.
    import test_mock_local_method from './test_mock_local_method.test';
    
    export default function testsuite() {
      test_mock_local_method();
    }
  5. Perform the test. The test case should be passed.