The automated testing framework is a comprehensive client-side testing system designed for multi-device, full-scenario verification. Built on DevEco Studio (IDE) and Hvigor (build system), it integrates capabilities such as UI testing (@ohos.UiTest) and unit testing (@ohos/hypium). Through standardized project structure, coding specifications, and execution workflows, the framework enables you to achieve efficient, high-quality verification.
This framework covers the unit testing framework, UI testing framework, and white-box performance testing framework.
This topic introduces the implementation of the unit testing and UI testing frameworks, aiming to help you understand and master the development workflow and implementation details of the automated testing framework. The key steps are as follows:

This section details the development workflow and implementation of the automated testing framework, focusing on unit testing and UI testing. You can apply these automated testing approaches to your apps according to specific service scenarios.
The unit testing framework uses mocking to isolate the code under test from external dependencies. This allows for fast, isolated, and repeatable verification of app logic (such as utility functions or services) without needing to launch the entire app. This section utilizes the following features of this framework to implement unit tests.
Feature | Description | Usage Scenario |
|---|---|---|
Provides basic process APIs like describe and it to define test suites and test cases, and allows you to set preconditions and cleanup conditions for them. | Defining test suites and cases that require preconditions before execution or cleanup afterwards, such as setting up and clearing timers. | |
Uses assertion APIs such as assertEqual to verify whether an actual value matches the expected value. | Verifying if a function operates correctly. | |
Mocks functions of custom objects. | Mocking functions that depend on external resources or complex logic, such as relying on the return value of a network request. | |
Executes a test suite or case multiple times with different data. | Executing multiple test cases or suites that share parameters of the same type, such as during stress testing. |
This approach employs the UI testing framework's APIs to inject simulated input events (such as taps or swipes) to specific coordinates or components, automating UI interaction and verification. This section provides the following implementation solutions for different UI testing scenarios.
Scenario | How to Implement |
|---|---|
Finding a component | Create an On object, describe the target component by id or type, and then use findComponent() to locate the component based on its property requirements. |
Simulating text input | Use inputText() to simulate text input. |
Simulating a tap | Use the click property in Component or Driver to simulate a tap. |
Simulating a touchscreen swipe | Use the swipe() method to simulate swiping on a carousel. |
Waiting for page loading | Use waitForIdle() to wait until all components on the current UI become idle before proceeding to the next operation. |
The UI testing flowchart is as follows:

Since test scripts are written in DevEco Studio, you first need to download DevEco Studio and complete the environment setup.
Hypium is the testing framework for OpenHarmony. It provides the functionality to develop and execute test cases, and to display their execution results. Hypium is used for testing the APIs and UIs of apps built for the OpenHarmony platform. Open your test project in DevEco Studio and configure it using either of the following methods:
ohpm install @ohos/hypium@1.0.24 --save-dev

Import the required unit testing framework capabilities and dependent APIs in other test scripts, and develop the unit test script. For details, see Creating an ArkTS Test Case.
Start the page under test and verify that the page displayed on the device is the expected one. The flowchart is as follows:

In automated testing, the it function from the basic workflow capabilities is commonly used to define a test case, with its parameters listed in the following table.
Parameter | Type | Mandatory (Yes/No) | Description |
|---|---|---|---|
testCaseName | string | Yes | Name of a test case, used to identify the test case. |
attribute | TestType | Size | Level | Yes | Test type, used to categorize the test case. |
func | Function | Yes | Asynchronous function (async) containing the specific logic of the test case. |
After creating a test case with it, obtain the app's bundle name via AbilityDelegatorRegistry. Then, construct a Want object and call startAbility() to launch the app. After the app is loaded, call getCurrentTopAbility() to obtain the foreground page displayed on the device, and use expect() and assertEqual() to assert whether the current page is the expected launch page.
const delegator: abilityDelegatorRegistry.AbilityDelegator = abilityDelegatorRegistry.getAbilityDelegator();
export default function UITest() {
describe('UITest', () => {
/**
* Start the application to be tested.
*/
it('startApp', Level.LEVEL3, async (done: Function) => {
hilog.info(0x0000, 'testTag', '%{public}s', "UITest: TestUiExample begin");
// Initialize the Driver object.
const driver = Driver.create();
const bundleName = abilityDelegatorRegistry.getArguments().bundleName;
// Specify the bundle name and ability name of the application to be tested.
const want: Want = {
bundleName: bundleName,
abilityName: 'EntryAbility'
}
// Start the application to be tested.
await delegator.startAbility(want);
// Wait until the application starts.
await driver.waitForIdle(4000, 5000);
const ability: UIAbility = await delegator.getCurrentTopAbility();
hilog.info(0x0000, 'testTag', '%{public}s', "get top ability");
// Ensure that the top ability of the application is the specified ability.
expect(ability.context.abilityInfo.name).assertEqual('EntryAbility');
done();
})
// ...
})
} Use beforeAll() to define preconditions and afterAll() to define cleanup conditions. Preconditions execute once before all test cases start, and cleanup conditions execute once after all test cases finish.
let success = -1;
let timeout = 0;
beforeAll(() => {
// Preset increment action before all test cases of the test suite start.
success++;
// Set a timer before all test cases of the test suite start.
timeout = setTimeout(() => {
hilog.info(0x0000, 'testTag', '%{public}s', 'setTimeout');
}, 1000);
})
beforeEach(() => {
// Preset increment action before each test case of the test suite starts.
success++;
})
afterEach(() => {
hilog.info(0x0000, 'testTag', '%{public}s', `success: ${success}`);
})
afterAll(() => {
hilog.info(0x0000, 'testTag', '%{public}s', 'AfterAll executed');
hilog.info(0x0000, 'testTag', '%{public}s', `success: ${success}`);
// Clear the timer after all test cases of the test suite end.
clearTimeout(timeout);
}) Use assertUndefined() to check if a value is undefined, and use assertEqual() to verify if an actual value meets the expected value.
it('inputAccountLength', 0, () => {
let inputAccountLength = CommonConstants.INPUT_ACCOUNT_LENGTH;
// Check if INPUT_ACCOUNT_LENGTH is not undefined.
expect(inputAccountLength).not().assertUndefined();
expect(inputAccountLength).assertEqual(11);
}) Verify that the length and data type of the return value from a custom function in the mainViewModel class meet expectations.
it('getFirstGridData', 0, () => {
const firstGridData = mainViewModel.getFirstGridData();
// Verify if the return value of getFirstGridData is eight.
expect(firstGridData.length).assertEqual(8);
// Verify if the type of firstGridData[0] is 'ItemData'.
expect(firstGridData[0] instanceof ItemData).assertTrue();
}) Mock the getSwiperImages() function in the mainViewModel class and set the return value of the function after being mocked. After the test case execution, restore the mocked object's instance.
it('getSwiperImages', 0, () => {
const swiperImages = mainViewModel.getSwiperImages();
expect(swiperImages).assertInstanceOf('Array');
expect(swiperImages.length).assertEqual(4);
// Mock the getSwiperImages function of the mainViewModel class.
let mocker = new MockKit();
let getSwiperImages = mocker.mockFunc(mainViewModel, mainViewModel.getSwiperImages);
// The result '[]' is returned when the function is called with any arguments passed in.
when(getSwiperImages)(ArgumentMatchers.any).afterReturn([]);
expect(mainViewModel.getSwiperImages()).assertInstanceOf('Array');
expect(mainViewModel.getSwiperImages().length).assertEqual(0);
// Restore the mocked object instances.
mocker.clear(mainViewModel);
// Verify if the mocked object instances are restored.
expect(mainViewModel.getSwiperImages().length).assertEqual(4);
}) Data-driven testing requires ability capabilities. For details, see Defining Custom Ability and Resources. Example file content can be viewed in the corresponding module's build/{productName}/intermediates/src/ohosTest directory after test case execution.

After defining the ability, add configuration fields such as mainElement, pages, and abilities in 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"
],
"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",
"label": "$string:TestAbility_label",
"exported": true,
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:start_window_background"
}
]
}
}
The resources directory under build/{productName}/intermediates/src/ohosTest does not include icon files; you need to add them manually.
The data-driven capability determines how many times a test case runs and the parameters passed for each run, based on the test data configuration. This functionality relies on the data.json configuration file.
{
"suites": [
{
"describe": [
"MainViewModelTest"
],
"stress": 1,
"items": [
{
"it": "testDataDriverAsync",
"stress": 2,
"params": [
{
"name": "tom",
"value": 5
},
{
"name": "jerry",
"value": 4
}
]
},
{
"it": "testDataDriver",
"stress": 3
}
]
}
]
} For the stage model, import data.json into the TestAbility.ets file under the TestAbility directory within the test project and set the parameters before the execution of Hypium.hypiumTest().
export default class TestAbility extends UIAbility {
abilityDelegator: abilityDelegatorRegistry.AbilityDelegator;
constructor() {
super();
this.abilityDelegator = abilityDelegatorRegistry.getAbilityDelegator();
}
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onCreate');
hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? '');
hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:' + JSON.stringify(launchParam) ?? '');
let abilityDelegatorArguments: abilityDelegatorRegistry.AbilityDelegatorArgs;
abilityDelegatorArguments = abilityDelegatorRegistry.getArguments();
hilog.info(0x0000, 'testTag', '%{public}s', 'start run testcase!!!');
// Set the data before Hypium.hypiumTest() is executed.
Hypium.setData(data);
Hypium.hypiumTest(this.abilityDelegator, abilityDelegatorArguments, testsuite);
}
// ...
} Define test cases within the test suite (MainViewModelTest) configured in the data.json file. The test case names must match the it names under items in the configuration.
interface ParmObj {
name: string,
value: number
}
export default function MainViewModelTest() {
describe('MainViewModelTest', () => {
// ...
it('testDataDriverAsync', 0, async (done: Function, data: ParmObj) => {
// Use data object to receive parameters passed from data.json.
hilog.info(0x0000, 'testTag', '%{public}s', `name: ${data.name}`);
hilog.info(0x0000, 'testTag', '%{public}s', `value: ${data.value}`);
// The name passed in data.json is either 'tom' or 'jerry'.
expect(data.name === 'tom' || data.name === 'jerry').assertTrue();
// Check if the actual value and the expected value '4' are within the allowable error range '1'.
expect(data.value).assertClose(4, 1);
done();
});
// ...
})
} In the UI testing framework, you can use UiTest APIs to simulate operations like tap, double-tap, long-press, and swipe to verify UI behavior in your app.
Match the target component using an On object, then simulate text input using inputText().
it('accountInputText', TestType.FUNCTION, async () => {
let driver = Driver.create();
// Match TextInput component by id.
let on = ON.id('account');
let accountInput = await driver.findComponent(on);
await accountInput.inputText('123456');
let account = await accountInput.getText();
expect(account).assertEqual('123456');
}) Use click() to simulate a touchscreen tap to dismiss the keyboard. Then, find the Button component using findComponent() and click it to perform a login action.
it('loginButton', TestType.FUNCTION, async () => {
let driver = Driver.create();
// Click the location of the confirm button in the input method to collapse the input method.
await driver.click(1196, 2511);
await driver.waitForIdle(2000, 3000);
// Check if the button is displayed.
let loginButton = await driver.findComponent(ON.type('Button'));
await loginButton.click();
// Wait the application for loading to the main page.
await driver.waitForIdle(4000, 5000);
}) After the Swiper component is loaded, use swipe() to simulate a swipe.
it('swiper', TestType.FUNCTION, async () => {
let driver = Driver.create();
// Wait the Swiper component for displaying in the current page.
await driver.waitForComponent(ON.type('Swiper'), 2000);
// Check if the Swiper component exists.
await driver.assertComponentExist(ON.type('Swiper'));
await driver.waitForIdle(1000, 2000);
// Swipe the carousel from right to left.
await driver.swipe(1100, 700, 100, 700, 3000);
// Wait for the swipe operation to complete.
await driver.waitForIdle(1000, 2000);
await driver.swipe(1100, 700, 100, 700, 3000);
await driver.waitForIdle(1000, 2000);
}) After using swipe() to switch pages, use waitForIdle() and waitForComponent() to wait for a Toggle component to appear, determining if the page navigation is complete.
it('setting', TestType.FUNCTION, async () => {
let driver = Driver.create();
await driver.swipe(1100, 1500, 100, 1500, 3000);
await driver.waitForIdle(1000, 2000);
// Match the Toggle component in the ListItem component.
let on = ON.type('Toggle').within(ON.type('ListItem'));
await driver.waitForComponent(on, 2000);
await driver.assertComponentExist(on);
// ...
}) After connecting to a target test device (such as a phone) or an emulator, run the test script by clicking the corresponding button in DevEco Studio or via the CLI. For details, see Running Test Scripts in DevEco Studio and Running Test Scripts in the CLI.
The result of implementing automated testing is shown in the following figure:

Symptom
When assertInstanceOf() is used to verify a custom data type, the error message "Error in getFirstGridData, [object Object] is [object Object]not ItemData" is displayed during script execution.

Possible Causes
When assertInstanceOf() is used for type assertion, it converts objects to strings for comparison. The custom data type is converted to [object Object], causing a mismatch with the expected type.
Solution
Perform an instanceof type check within expect() and use assertTrue() for verification. The modified sample code is as follows:
expect(firstGridData[0] instanceof ItemData).assertTrue();
Symptom
When inputText() is used to input text to the TextInput component, only digits can be input; letters and special characters cannot be input.
Possible Causes
The input box type is InputType.Number. The numeric input mode allows only digits (0-9).
Solution
Modify the input box type to InputType.USER_NAME, or to another appropriate type based on your service requirements, before conducting the test.
Symptom
When swipe() is used on the Swiper component, the first swipe fails to take effect, but subsequent swipes work as expected.
Possible Causes
The relevant component has not finished loading when the UI operation API is called.
Solution
Use waitForComponent() to wait for the component to finish loading before performing the UI operation.
The automated testing framework is a core element in building an efficient, stable, maintainable, and scalable testing system. Using this framework for app testing allows test cases to execute automatically without manual intervention, helping to reduce testing effort. When a test case fails, DevEco Studio enables you to quickly identify and pinpoint issues in the automated tests, helping reduce defects in your app before release.
This topic explains how to implement automated testing by using the basic process and assertion capabilities of the unit testing framework, along with the UiTest APIs of the UI testing framework.
If you need to perform performance tests on app logic, see PerfTest User Guide.