Generate unit test cases for OpenHarmony C/C++ code that comply with the testfwk_developer_test framework specification.
Anti-Patterns - Absolute Prohibitions
NEVER do the following, otherwise the tests will fail to compile or run:
| Prohibited item | Reason | Correct approach |
|---|---|---|
NEVER omit using namespace testing::ext; |
Macro definitions such as HWTEST/HWTEST_F are in this namespace; omission will cause compilation failure | The file header must include this statement |
NEVER use native GTest TEST() or TEST_F() |
OpenHarmony gatekeeping cannot recognize it, and the test level parameter is missing | Uniformly use HWTEST or HWTEST_F |
| NEVER forget the test level parameter in the HWTEST macro | TestSize.Level1-4 is the basis for gatekeeping judgment; omission will be rejected | Must specify e.g. TestSize.Level1 |
NEVER omit import("//build/test.gni") |
The ohos_unittest template is defined in this file; omission will report "template not found" | The first line of BUILD.gn must import |
| NEVER use an absolute path in module_out_path | The output path format must be 子系统名/模块名; a GN path will cause an error |
Use e.g. hiviewdfx/hiview_test |
| NEVER forget the cflags_cc bypass when accessing private members | Private members cannot be accessed directly; it will report an "is private" error | Add -Dprivate=public -Dprotected=public |
| NEVER mix up test type concepts | OpenHarmony has FUNC/PERF/RELI/SECU/FUZZ types, which differ from GTest concepts | Use the types defined by OH in @tc.type |
| NEVER forget to initialize the test object in SetUp | An uninitialized pointer will cause SEGFAULT or NULL pointer errors | Ensure objects such as detector_ are created in SetUp |
| NEVER omit the gtest_main dependency | Omission will cause the link error "undefined reference to main" | deps must include //third_party/googletest:gtest_main |
Execution Flow
环境确认 → 分析源码 → 测试策略 → 测试设计 → 用例规划 → 编写测试文件 → BUILD.gn → 验证
Step Zero: Environment Confirmation
Goal: Confirm the test file placement location and compilation environment configuration.
MANDATORY - READ ENTIRE FILE: Before environment confirmation, MUST read test-framework.md completely to understand:
- Differences and selection among ohos_unittest/ohos_moduletest/ohos_fuzztest
- API version correspondence
- Test framework directory structure
Light Loading (read only if needed):
framework-quickref.md- Test framework quick reference table (macros + levels + comments + naming)
Do NOT Load: build-rules.md, error-matrix.md (not involved in this step)
Checklist (must be completed)
| Check item | Specification | Example |
|---|---|---|
| Test file location | Module root directory/test/unittest/ | base/hiviewdfx/hiview/test/unittest/ |
| Mock file location | test/mock/ | base/hiviewdfx/hiview/test/mock/ |
| BUILD.gn location | Under the test/ directory | base/hiviewdfx/hiview/test/BUILD.gn |
| BUILD.gn entry | group("unittest") { testonly = true } | -- |
| Source path format | GN style //base/xxx | //base/hiviewdfx/hiview |
Output Format
After confirmation is complete, output:
## 环境确认完成
- 模块根目录: base/xxx/yyy
- 测试目录: base/xxx/yyy/test/unittest/
- 测试输出路径: subsystem/module_test
- 源码GN路径: //base/xxx/yyy
Existing Test Analysis (Optional)
Objective: If the target module already has existing test code, first analyze the existing style to ensure the newly generated tests are consistent with it.
Use the analyze-existing-tests.py script to analyze existing tests:
python scripts/analyze-existing-tests.py <test_directory> --output style_report.md [--encoding utf-8] [--verbose]
Parameter Description:
| Parameter | Description |
|---|---|
directory |
Test case directory path (required) |
--output, -o |
Output report file path (optional; if not specified, output to terminal) |
--encoding, -e |
File read encoding (default utf-8) |
--verbose, -v |
Output detailed debug information |
When to Use:
- When the target module already has test files under the
test/unittest/directory,recommendedto run this script first - For a brand-new module with no existing code, skip this step
Purpose of Analysis Results:
- Macro selection: Refer to whether the existing code mainly uses HWTEST or HWTEST_F
- Level format: Refer to whether the existing code uses
TestSize.Level1orLevel1 - Naming style: Refer to the test case naming pattern of the existing code (
FuncName_001vsTestSuite_FuncName_001) - Comment style: Refer to the @tc comment format of the existing code
Step 1: Analyze the source code under test
Objective: Parse the source code and extract the structured information required for testing.
Light Loading (read only if needed):
test-framework.md- Continue reading when not completed in Step 0framework-quickref.md- When referring to naming conventionsreal-patterns.md- When real code examples are needed for reference
Do NOT Load: build-rules.md, error-matrix.md, assertion-gmock-guide.md (not involved in this step)
Parsing Points
| Parsing Category | Key Information | Method |
|---|---|---|
| Class structure | Class name, inheritance relationships, member variables | Extract the class definition block |
| Public methods | Function signature, return type, parameter list | Analyze function declarations in the public section |
| Function logic | Branch conditions, exception handling, boundary checks | Extract if/try/return logic |
| Data types | Enum, constant, struct definitions | Extract enum/const/struct |
Output format (structured report)
## 源码分析报告
### 文件信息
- 源文件: //base/xxx/src/file.cpp
- 头文件: //base/xxx/include/file.h
- 命名空间: OHOS::XXX
### 公开方法列表
| 方法 | 签名 | 分支逻辑 | 边界条件 |
| GetSectionInfo | bool GetSectionInfo(const string&, Info&) | 空字符串返回false | 空字符串 |
| ResetSection | bool ResetSection(const string&) | 空字符串返回false | 空字符串 |
Step 2: Formulate a test strategy
Objective: Based on the source code analysis, formulate the test scope, types, priorities, and coverage targets.
Light Loading (read only if needed):
test-strategy-method.md- Code feature → test strategy mapping tableframework-quickref.md- Refer to the test level selection decision tree
Do NOT Load: build-rules.md, error-matrix.md, test-case-spec.md
Strategy Decision Table
| Method Type | Test Scope Determination | Priority Suggestion |
|---|---|---|
| public method | Must test | Core functionality P1, auxiliary functionality P2 |
| static method | Must test (independently testable) | P1 |
| virtual method | Must test (cover derived classes) | P1/P2 |
| private method | Do not test directly | Cover indirectly through public methods |
| Logic feature | Test type selection | |
| ---- | ----------- | |
| Computation logic | FUNC (functional test) | |
| Performance-sensitive | PERF (Performance Testing) | |
| Exception Handling | RELI (Reliability Testing) | |
| Security Check | SECU (Security Testing) |
Output Format
## 测试策略
| 方法 | 测试判定 | 测试类型 | 优先级 |
| GetSectionInfo | 必测(核心功能) | FUNC | P1 |
| ResetSection | 必测(含状态处理) | FUNC | P1 |
### 覆盖率目标
- 语句覆盖率: ≥80%
- 分支覆盖率: ≥70%
- 函数覆盖率: 100%
Step 3: Perform Test Design
Objective: Combine black-box and white-box testing methods to transform the test strategy into specific test scenario designs.
Light Loading (read only if needed):
test-strategy-method.md- Reference for parameter boundary value designframework-quickref.md- Reference test level assignment
Do NOT Load: build-rules.md, error-matrix.md, test-case-spec.md
Test Scenario Design Template (Required)
Fill in the following table for each method:
## [函数名] 测试场景设计
| 编号 | 场景类型 | 场景描述 | 输入数据 | 预期输出 | 测试等级 |
| T01 | 正常 | [具体场景] | [参数值] | [返回值/状态] | Level1 |
| T02 | 异常 | [错误场景] | [触发错误的输入] | [错误码/false] | Level2 |
| T03 | 边界 | [边界值] | [INT_MAX/空字符串等] | [预期行为] | Level2 |
| T04 | 状态 | [状态依赖] | [前置状态描述] | [状态变化结果] | Level2 |
Scenario Design Key Points
| Parameter Type | Normal Input Design | Boundary Test Points |
|---|---|---|
| int/long | Typical positive value, negative value, zero value | INT_MIN, INT_MAX, 0, -1 |
| string | Non-empty string | Empty string, extra-long string |
| Pointer | Valid object pointer | nullptr |
| Container | Non-empty container | Empty container, single element |
Step 4: Plan Test Cases
Objective: Map test scenarios to specific test cases, and determine naming and level assignment.
MANDATORY - READ ENTIRE FILE: Before planning cases, MUST read naming-convention.md to understand:
- Recommended new generation rules:
[FunctionName]_[001-999] - Compatible with historical existing style (for analysis reference only)
- @tc.name naming convention
Light Loading (read only if needed):
framework-quickref.md- Test level selection decision treereal-patterns.md- Reference historical existing naming format (during analysis)
Do NOT Load: build-rules.md, error-matrix.md
Case Planning Template (Required)
## [函数名] 用例规划
| 用例编号 | 用例名称 | 对应场景 | 测试等级 | 测试宏 |
| 001 | GetSectionInfo_001 | T01 正常获取 | Level1 | HWTEST_F |
| 002 | GetSectionInfo_002 | T02 空字符串 | Level2 | HWTEST_F |
Test Macro Selection Decision Table
| Situation | Test Macro Selection | Reason |
|---|---|---|
| No initialization/cleanup needed | HWTEST(A, B, TestSize.Level1) |
Independent test, no Setup/Teardown |
| Initialization before and after test needed | HWTEST_F(A, B, TestSize.Level1) |
SetUp/TearDown needed |
| Multi-threaded testing | HWMTEST_F(A, B, C, D) |
D is the number of threads |
| Parameterized testing | HWTEST_P(A, B, C) |
Multi-set data testing |
Step 5: Write Test Files
Objective: Generate test code files that comply with the specifications.
MANDATORY - READ ENTIRE FILE: Before writing code, MUST read:
test-case-spec.md- Complete test file structure, Anti-Patterns prohibition listframework-quickref.md- HWTEST macro usage, test levels, @tc comment formatassertion-gmock-guide.md- Mock configuration (if Mock is needed)
Light Loading (read only if needed):
real-patterns.md- When real code examples need to be referencednaming-convention.md- Detailed naming convention description
Do NOT Load: build-rules.md, error-matrix.md (this step does not involve BUILD.gn and error troubleshooting)
Test File Structure Template
MANDATORY - READ ENTIRE FILE: Refer to the complete template test-template.cpp(~75 lines), including:
- Copyright notice, header file inclusion, namespace declaration
- Test class definition (SetUpTestCase/TearDownTestCase/SetUp/TearDown)
- @tc comment format, HWTEST_F macro example, assertion usage
Key Elements:
using namespace testing::ext;→ MUST include (HWTEST macro is in this namespace)SetUp()Initialize test object → MUST complete (otherwise SEGFAULT)- Naming format: recommended
[FunctionName]_[001], see naming-convention.md for details
Naming Key Points(see naming-convention.md for details):
- Recommended:
[FunctionName]_[001](e.g.GetSectionInfo_001) - History:
TestSuiteFunction_001(e.g.BBoxDetectorUnitTest001, newly generated imitations are not recommended)
Assertion Usage Rules
See test-case-spec.md Anti-Patterns prohibition list.
Core Principles:
- Precondition checks (pointer non-null, state validation) → MUST use
ASSERT_*(terminate on failure) - Result validation (output/state validation) → MUST use
EXPECT_*(continue on failure)
Step Six: Write BUILD.gn
Goal: Configure the compilation rules for the test target.
MANDATORY - READ ENTIRE FILE: Before writing BUILD.gn, MUST read build-rules.md to understand:
- Test template type selection (ohos_unittest vs ohos_moduletest)
- deps vs external_deps decision rules
- cflags_cc access control bypass configuration
- Complete BUILD.gn template
Do NOT Load: framework-quickref.md, error-matrix.md, real-patterns.md (this step does not involve test code and examples)
BUILD.gn Template
MANDATORY - READ ENTIRE FILE: Refer to the complete template build-template.gn(~45 lines), including:
- import statement, module_output_path configuration
- config block, ohos_unittest definition, group definition
- Complete examples of deps/external_deps/cflags_cc/defines
Key Configuration Items:
| Configuration Item | Description | Required | Common Errors |
|---|---|---|---|
import("//build/test.gni") |
Test template definition | Required (first line) | Missing → template not found |
module_out_path |
Output path, format 子系统/模块 |
Required | Using an absolute path → error |
deps |
Internal dependency, including gtest_main | Required | Missing gtest_main → undefined reference to main |
external_deps |
Cross-subsystem dependency | As needed | Format error → link failure |
cflags_cc |
Access control bypass | As needed (when testing private) | Missing → 'xxx' is private |
Step Seven: Verification and Debugging
Goal: Confirm that the test cases can compile and run correctly.
MANDATORY - READ ENTIRE FILE: Before verification, MUST read error-matrix.md to understand:
- Compilation error matrix (symptom → cause → fix)
- Runtime error matrix
- Gate rejection errors
- Error troubleshooting process
Do NOT Load: framework-quickref.md, build-rules.md, real-patterns.md (already loaded in previous steps)
Compilation Commands
./build.sh --product-name <product> --build-target BBoxDetectorUnitTest
Quick Troubleshooting of Common Compilation Errors
| Error | Cause | Solution |
|---|---|---|
fatal error: xxx.h: No such file |
include_dirs missing | Add include_dirs in the config block |
undefined reference to xxx |
deps missing | Check deps and external_deps |
'xxx' is private |
Access control | Add cflags_cc: -Dprivate=public |
template 'ohos_unittest' not found |
Missing import | Add on the first line import("//build/test.gni") |
Quick Reference
For the complete quick reference table of test levels, test macros, and comment formats, see framework-quickref.md, including:
- Level0-Level4 level definitions, selection decision tree, level assignment for common scenarios
- HWTEST/HWTEST_F macro syntax and gate mandatory requirements
- @tc.type test type quick reference (FUNC/PERF/RELI/SECU/FUZZ)
- Naming convention quick reference (recommended new generation rules vs compatible historical legacy style)
References navigation
Detailed documentation is located in the references/ directory, loaded according to step requirements:
| File | Content | Loading timing |
|---|---|---|
test-framework.md |
Test framework overview, API version correspondence | Step 0 MANDATORY |
framework-quickref.md |
Test framework quick reference table (macros + levels + comments + naming) | Step 0-5 MANDATORY/Light |
test-case-spec.md |
Complete test file structure, Anti-Patterns | Step 5 MANDATORY |
naming-convention.md |
Naming conventions (recommended new rules vs historical compatibility) | Step 4 MANDATORY |
build-rules.md |
BUILD.gn decision rules, complete template | Step 6 MANDATORY |
error-matrix.md |
Error troubleshooting matrix (compilation + runtime + gate) | Step 7 MANDATORY |
assertion-gmock-guide.md |
Mock configuration (BUILD.gn integration + real examples) | Step 5 Light(when Mock is needed) |
real-patterns.md |
Real repository examples (historical format annotated) | Step 1-5 Light Loading |
test-strategy-method.md |
Test strategy design method | Step 2-3 Light Loading |
Examples navigation
Complete template examples are located in the examples/ directory:
| File | Content | Purpose |
|---|---|---|
test-template.cpp |
Complete test file example (copyright + class definition + test cases) | Step 5 reference complete code structure |
build-template.gn |
Complete BUILD.gn example (import+config+ohos_unittest) | Step 6 reference complete configuration structure |
Loading timing: MANDATORY - READ ENTIRE FILE (Step 5, Step 6)
Input information requirements
| Information | Required | Description |
|---|---|---|
| Source code location | Required | File path or function name |
| Requirement number | Optional | @tc.require fill-in content, empty when there is no requirement number |
| Test level | Optional | Default Level1 |
| Whether to generate BUILD.gn | Optional | Generated by default |
Getting started
When the user requests test generation, execute according to the workflow:
- Environment confirmation → read test-framework.md + framework-quickref.md
- Analyze source code → output source code analysis report
- Test strategy → read test-strategy-method.md + framework-quickref.md → output strategy table
- Test design → output scenario design table
- Test case planning → read naming-convention.md + framework-quickref.md → output test case planning
- Write test file → read test-case-spec.md + framework-quickref.md + assertion-gmock-guide.md → generate .cpp
- Write BUILD.gn → read build-rules.md → generate .gn
- Verification → read error-matrix.md → provide compilation commands