目录

Instrument Test

Creating an ArkTS Test Case

[h2]Creating a Default Test Case

  1. Open the .ets file of the HAP, HAR, or HSP module to be tested in the project directory, move the cursor to any position in the code, and then right-click the code and choose Show Context Actions > Create Instrument Test, or press Alt+Enter (Option+Enter on macOS) and click Create Instrument Test in the dialog box displayed.

  2. In the Create Instrument Test dialog box, set the following parameters:

    • Testing library: test type. The default value is DECC-ArkTSUnit for an ArkTS project and DECC-JSUnit for a JS project.
    • ArkTS name: name of the created test file, which contains test cases. The test file name must be unique in the project directory, and allows only letters, digits, underscores (_), and dots (.).
    • Destination package: location where the test file is stored. You are advised to store it in the test directory of the module to be tested.

  3. DevEco Studio automatically generates the corresponding test class in the ohosTest/ets/test directory. In the test class, DevEco Studio generates the case template of the corresponding method. You need to develop the specific test code based on the service logic. For details, see arkXtest User Guide.

    • You can also manually create a test case under ohosTest\ets\test and add the corresponding test class to the List.test.ets file. All the files in the ohosTest\ets\test directory must end with .test.ets. Otherwise, "Error: Test files must end with '.test.ets'." will be displayed when the files are executed. If this occurs, click Fix. DevEco Studio automatically corrects the file names in the directory.
    • If it is your first time to run UITest on a HarmonyOS device, run the hdc -n shell param set persist.ace.testmode.enabled 1 command to enable UITest capabilities.

[h2]Defining Custom Ability and Resources

Since 5.0.3.403, the ohosTest directory in newly created projects and modules no longer includes the testability, testrunner, and resources directories by default. (These directories are retained in existing projects.) If new projects require the use of abilities or resources, you need to create them manually.

To use ability capabilities, you must also create the testrunner directory and the OpenHarmonyTestRunner.ets file.

Table 1 Comparison of the ohosTest directory between new and old versions

New version

Old version

  1. Create the following directories or files. After running the instrument test case, you can view sample file contents in the .test/{productName}/intermediates/src/ohosTest directory (for DevEco Studio 6.1.0 Beta1 or later) or the build/{productName}/intermediates/src/ohosTest directory (for versions earlier than DevEco Studio 6.1.0 Beta1) of the corresponding module. {productName} specifies the currently effective product, which can be viewed by clicking in the upper-right corner of DevEco Studio.

    • testability > TestAbility.ets
    • testability > pages > Index.ets
    • testrunner > OpenHarmonyTestRunner.ets
    • resources > base > element > color.json
    • resources > base > element > string.json
    • resources > base > profile > test_pages.json

  2. Add the ability configuration fields mainElement, pages, and abilities to the module.json5 file. For details about the fields, see module.json5 Configuration File.

    {
      "module": {
        "name": "entry_test",
        "type": "feature",
        "description": "$string:module_test_desc",
        "mainElement": "TestAbility",                                   // Corresponds to the ability name in the abilities section below.
        "deviceTypes": [
          "phone",
          "tablet",
          "2in1"
        ],
        "deliveryWithInstall": true,
        "installationFree": false,
        "pages": "$profile:test_pages",                                 // Corresponds to the test_pages.json file under resources > base > profile.
        "abilities": [                                                  // Configuration of the ability to add.
          {
            "name": "TestAbility",
            "srcEntry": "./ets/testability/TestAbility.ets",
            "description": "$string:TestAbility_desc",
            "icon": "$media:icon",    // Ensure that the referenced resources exist.
            "label": "$string:TestAbility_label",
            "exported": true,
            "startWindowIcon": "$media:icon",
            "startWindowBackground": "$color:start_window_background"
          }
        ]
      }
    }

Running a Test Case

[h2]Performing Local Tests in Running Mode

Before running test cases, connect the device and your PC, build your project into a signed HAP, and install and run the HAP on the device or Emulator. For details, see Running Your App on a Local Real Device or Running Your App on the Emulator.

You can run all test cases in a project directory (test), run test cases from a file (such as Ability.test.ets), run all tests associated with a test suite (describe), and run a specific test method (it).
  • To run test cases in a project directory, right-click the project directory and choose Run 'test file name' from the shortcut menu.

  • To run test cases from a file, open the file and click the green button on the left of the test suite.

  • To perform an instrument test based on custom configuration, create a test case task and perform either of the following operations:
    • Choose Run > Run 'test name'.
    • In the upper right corner of DevEco Studio, select a test task and click on the right.

View the test result after the test is complete.

[h2]Performing Instrument Tests in Debug Mode

Compared with the running mode, the debug mode provides breakpoint management. When a breakpoint is hit, you can perform single stepping, step-in, step-out, and stop-over operations as required. You can also view the thread stacks, variables, and expressions to quickly locate faults.

The following uses a test file as an example. After adding breakpoints, right-click the target file in the project directory and choose Debug 'Test file name' from the shortcut menu to perform a test task in debug mode.

When a breakpoint is hit, the Debug window is displayed. You can perform breakpoint management and basic debugging in this window. When a breakpoint is hit, you can view the variables and stack information of the current thread.

Right-click in the code editor window. The shortcut menu shows the functions specific to the debug mode, including Evaluate Expression, Run to Cursor, Force Run to Cursor, Add to Watches, and Add Inline Watch.

After the test is complete, view the test result on the console.

You can set the type of code to be debugged in DevEco Studio. For details, see Setting the Debug Type.

[h2]Performing Instrument Tests with Code Coverage

DevEco Studio provides the code coverage for instrument tests.

You can specify the local files or remote source code HAR packages to be included in or excluded from the coverage statistics. For details, see Filtering Files for Coverage Testing.

You can run all test cases in a project directory (test), run test cases from a file (such as Ability.test.ets), run all tests associated with a test suite (describe), and run a specific test method (it).

To run test cases from a file, use either of the following methods:

After the test starts, the build process begins, and the Cover tab appears at the bottom. Once the build is complete, the Cover tab will automatically open. After the test task is finished, the path to the test report will be printed on the tab page.

Click the path link to open the report and view the ArkTS code coverage details. For details about the coverage rate, see Viewing Coverage Reports.

On the Cover tab page, you can click the rerun button to re-execute the test case based on the previous settings.

(Optional) Customizing a Test Case Task

By default, test cases can be directly executed. To customize a test case task, perform the following steps:

  1. Choose Run > Edit Configurations from the main menu on the toolbar.
  2. On the Run/Debug Configurations page, click + and choose Instrument Test from the drop-down list.

  3. Set parameters, and click OK.

    • If the module depends on a HAP, set the HAP installation mode in advance to Keep Application Data. This way, the HAP will be installed in overwrite mode, ensuring that the app/atomic service cache data is retained.
    • When your project involves HAP/HSP modules that directly depend on other HSP modules (for example, an entry module depending on an HSP module) or indirectly depend on other modules (for example, an entry module depending on an HAR module, which then depends on an HSP module), you must install both the module packages and all their dependencies on the device during testing. In this case, you can select Auto Dependencies, which ensures that all required dependencies are automatically installed on the device. This feature is enabled by default for convenience.
    • If UI testing is not involved, select Only OhosTest Package. This ensures that only the OhosTest package is sent to the device, omitting the HAP/HSP package. As a result, the time taken for package deployment is significantly shortened.

[h2]Filtering Test Cases

  1. Set a filter parameter for your test cases via the second parameter of it() when writing test cases. This parameter is used to add annotations to a test case. The default value 0 indicates that the test case has no annotation.

  2. On the Run/Debug Configurations page, click in Test Args and add test parameters in the Test Args dialog box displayed.

    For example, set level to 1 and size to medium.

    Table 2 Parameter description

    Key

    Description

    Value Range

    level

    Level of the test case.

    0 to 4, for example, -s level 1.

    size

    Granularity of the test case.

    small, medium, or large, for example, -s size small.

    testType

    Type of the test case.

    function, performance, power, reliability, security, global, compatibility, user, standard, safety, or resilience, for example, -s testType function.

  3. Run the test cases. Only the test cases that match the filter criteria will be executed.

[h2]Setting the Debug Type

Choose Run > Edit Configurations. In the Run/Debug Configurations dialog box, select Instrument Test, click the Debugger tab, and set Debug type.

By default, the debug type is Detect Automatically. The table below describes the debug types.

Debug Type

Code Type

Detect Automatically

Code automatically detected. The debugger is selected based on the programming languages involved in the project module and its dependent modules.

If a native module is detected, both the PandaDebugger and Native debug windows are displayed; if no native module is detected, only the PandaDebugger debug window is displayed.

ArkTS/JS

ArkTS/JS. The PandaDebugger debug window is displayed.

Native

C++. The Native debug window is displayed.

Dual(ArkTS/JS + Native)

ArkTS/JS and C/C++. Both the PandaDebugger and Native debug windows are displayed.

When debugging C++ code, ensure that the Address Sanitizer configuration of the current module is the same as that of all dependent HSP modules. Otherwise, the breakpoint of the C++ code may fail to be entered.

[h2]ASan Detection

In instrument tests, you can run ASan detection for C/C++ methods. For details about ASan, see ASan. This feature does not apply to JavaScript.

  1. In the Run/Debug Configurations window, select an instrument test, click the Diagnostics tab, and select Address Sanitizer. Then both the test package and the source package will have ASan enabled.

  2. If a local library is referenced, set arguments to -DOHOS_ENABLE_ASAN=ON in the build-profile.json5 file of the library module. This allows the .so file to be compiled in ASan mode.

  3. Execute test cases.
  4. When a memory error occurs, the ASan log information will be displayed. You can click the link in the information to go to the code that causes the memory error.

Testing C++ Code

As of DevEco Studio 6.0.0 Beta5, support for testing C++ code has been added, including the ability to run or debug C++ test code and collect code coverage statistics for C++.

Since the C++ test shared library (.so) cannot be executed directly on the device, it must be launched via Node-API from ArkTS/JS code to run the C/C++ test cases.

[h2]Running C++ Test Code

  1. To create a C++ test directory, right-click the ohosTest directory and choose New > C/C++ File(Napi) from the shortcut menu. This will generate the C++ test directory under ohosTest. Taking the entry module as an example, the resulting directory structure is as follows:
    • src > ohosTest > cpp > types: a collection of C++ API description files.
    • src > ohosTest > cpp > types > libentry_test > index.d.ts: file that describes the C++ API behavior, such as the API name, input parameters, and output parameters.
    • src > ohosTest > cpp > types > libentry_test > oh-package.json5: configuration of the entry to the .so third-party package declaration file and third-party package names.
    • src > ohosTest > cpp > CMakeLists.txt: CMake configuration file, which provides CMake build scripts.
    • src > ohosTest > cpp > napi_init.cpp: file that defines C++ APIs.

    The C++ test directory generated by DevEco Studio does not include a C++ testing framework. You need to select and use an open-source testing framework.

  2. Launch the C++ test via ArkTS test cases. The example is as follows:
    // ArkTS test file Ability.test.ets
    import entryTest from 'libentry_test.so';
    export default function abilityTest() {
      describe('ActsAbilityTest', () => {
        // ...
        it('testNative', 0, () => {
          hilog.info(0x0000, 'testTag', '%{public}s', 'testNative it begin');
          let result = entryTest.runNativeTest();
          hilog.info(0x0000, 'testTag', '%{public}s', result)
          expect(result).assertContain("ended");
        })
      })
    }
  3. Run the testNative test cases and check the test results.

[h2]Collecting Code Coverage

DevEco Studio does not collect C++ code coverage by default and needs to be enabled as follows:

  1. Add the following code to CMakeLists.txt in the test directory to enable coverage compilation instrumentation.
    // For versions earlier than DevEco Studio 6.0.2 Beta1
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-instr-generate -fcoverage-mapping")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-instr-generate -fcoverage-mapping")
    
    // For DevEco Studio 6.0.2 Beta1 and later versions, OHOS_TEST_COVERAGE is true in coverage mode and false in debug/run mode.
    if(OHOS_TEST_COVERAGE)
      set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-instr-generate -fcoverage-mapping")
      set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-instr-generate -fcoverage-mapping")
    endif()
  2. In the RunNativeTest method of the napi_init.cpp file, call the __llvm_profile_write_file method to save the coverage data to the c++_coverage.profraw file under the /data/storage/el2/base path on the device. This path and file name cannot be modified. Example code is as follows:

    extern "C" {
        void __llvm_profile_set_filename(char *);
        int __llvm_profile_write_file(void);
    }
    
    static napi_value RunNativeTest(napi_env env, napi_callback_info info)
    {
        char filename[256];
        snprintf(filename, sizeof(filename), "/data/storage/el2/base/c++_coverage.profraw"); // Coverage report file path and file name, which cannot be changed.
        __llvm_profile_set_filename(filename);
        // Start the test.
        // ...
        // End the test and save the data.
         __llvm_profile_write_file();
        // ...
    }
    
    
  3. Right-click the ArkTS test file and choose Run 'Test file name' with Coverage from the shortcut menu to run the coverage test.

    After the test starts, the build process begins, and the Cover tab appears at the bottom. Once the build is complete, the Cover tab will automatically open. After the test task is finished, the path to the test report will be printed on the tab page.

    Click the link to open the report and view details of C++ code coverage.

Running Tests via the CLI

Run the following command in the root directory of the project to perform the instrument test:
hvigorw onDeviceTest -p module={moduleName} -p coverage={true|false} -p scope={suiteName}#{methodName} -p ohos-debug-asan={true|false} -p patch={patchPath}
  • module: module on which the test is performed. By default, the test cases of all modules are performed.
  • coverage: whether to generate a coverage report. The default value is true. When this feature is enabled (true), two reports are generated in the <module-path>/.test/default/outputs/ohosTest/reports directory, one in HTML format (index.html) and the other in JSON format (coverageReport.json). For details, see Viewing Coverage Reports.

    If C++ code coverage testing is enabled, a coverage report will be generated at the path: <module-path>/.test/default/outputs/ohosTest/cpp_reports/index.html.

  • scope: test case, in the format of {suiteName}#{methodName}, or test suite, in the format of {suiteName} for execution. By default, all cases of the current module are executed.
  • ohos-debug-asan: whether to enable ASan detection. The default value is false. This field is supported since DevEco Studio 5.1.1 Beta1.

    ASan log path: <module-path>/.test/default/intermediates/ohosTest/coverage_data

  • patch: (optional) path to the code patch file for incremental code coverage statistics. Only absolute paths are supported, and the file suffix must be .patch or .diff. Such files can be generated using commands such as git diff. This field is supported since version 26.0.0.
  • When you run tests via the CLI, the product parameter cannot be configured and defaults to default.
  • Multiple values of module and scope can be specified, separated by commas (,).

Path of the test result file: <module-path>/.test/default/intermediates/ohosTest/coverage_data/test_result.txt