oh-ut-generator
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOpenHarmony Unit Test Generator
OpenHarmony单元测试生成器
Overview
概述
Generate comprehensive C++ unit tests for OpenHarmony code following HWTEST_F framework conventions.
遵循HWTEST_F框架规范,为OpenHarmony代码生成全面的C++单元测试。
Key Features
核心特性
- Automatic Test Generation: Create test cases for normal/exception/boundary scenarios
- Mock Object Support: Mock class creation and EXPECT_CALL/ON_CALL setup
- BUILD.gn Configuration: Automatic dependency matching with source files
- Coverage Optimization: 75% minimum coverage, targeting 85%+
- Code Style Consistency: Maintains consistency with existing test patterns (>=70% threshold)
- NDK/NAPI Support: Special handling for NDK interfaces (7088+ OH_xxx) and NAPI functions (302+ napi_xxx)
- CJSON Testing: Complete support for CJSON library testing patterns
- 自动测试生成:为正常/异常/边界场景创建测试用例
- Mock对象支持:Mock类创建及EXPECT_CALL/ON_CALL配置
- BUILD.gn配置:自动匹配源文件的依赖关系
- 覆盖率优化:最低覆盖率75%,目标85%以上
- 代码风格一致性:与现有测试模式保持一致(一致性阈值≥70%)
- NDK/NAPI支持:对NDK接口(7088+ OH_xxx)和NAPI函数(302+ napi_xxx)提供特殊处理
- CJSON测试:全面支持CJSON库测试模式
Usage
使用方法
Invoke this skill when you need to generate unit tests for OpenHarmony C++ source files.
当你需要为OpenHarmony C++源文件生成单元测试时,即可调用此能力。
Supported Scenarios
支持场景
- Single File Testing: Generate tests for all functions in a source file
- Specific Function Testing: Generate tests for a specific function only
- Test File Extension: Append new test cases to existing test files
- Mock Generation: Automatically create mock classes for dependencies
- 单文件测试:为源文件中的所有函数生成测试用例
- 特定函数测试:仅为某个特定函数生成测试用例
- 测试文件扩展:在现有测试文件中追加新的测试用例
- Mock生成:自动为依赖项创建Mock类
Critical Requirements
关键要求
Test Implementation Completeness
测试实现完整性
- Complete Implementation Only: Every test case must have complete implementation
- No Comments-Only Tests: Forbidden to generate tests with only comments or empty bodies
- Mock Usage: If Mock objects are created, they must be used with EXPECT_CALL/ON_CALL
- Branch-Assertion Correspondence: Branch assertions must match branch logic exactly
- 仅允许完整实现:每个测试用例必须具备完整的实现
- 禁止仅注释测试:不允许生成只有注释或空实现的测试用例
- Mock使用规范:若创建了Mock对象,必须配合EXPECT_CALL/ON_CALL使用
- 分支断言对应:分支断言必须与分支逻辑完全匹配
Coverage Requirements
覆盖率要求
- Minimum: 75% branch and line coverage (mandatory)
- Target: 85% branch and line coverage (goal)
- Scope: Boundary conditions, exception paths, normal paths, all conditional branches
- 最低标准:75%的分支和行覆盖率(强制要求)
- 目标标准:85%的分支和行覆盖率(理想目标)
- 覆盖范围:边界条件、异常路径、正常路径、所有条件分支
Code Style Consistency
代码风格一致性
When existing test files exist:
- Smart Pointer Type: Must match existing code (sptr/wptr vs std::shared_ptr)
- Mock Usage: Must match existing Mock patterns
- Assertion Style: Must match existing assertion preferences (EXPECT_ vs ASSERT_)
- Test Structure: Must match existing test fixtures and naming patterns
Consistency Threshold: >=70% for important scenarios
当存在现有测试文件时:
- 智能指针类型:必须与现有代码保持一致(sptr/wptr vs std::shared_ptr)
- Mock使用方式:必须与现有Mock模式匹配
- 断言风格:必须与现有断言偏好一致(EXPECT_ vs ASSERT_)
- 测试结构:必须与现有测试夹具和命名模式匹配
一致性阈值:重要场景下≥70%
Security Coding
安全编码
- Memory Management: Match original function's smart pointer usage pattern
- Variable Initialization: All variables must be initialized
- Boundary Checks: Required before array/container access
- Null Pointer Checks: Required before pointer dereference
- Return Value Checks: Required for critical functions
- 内存管理:与原函数的智能指针使用模式保持一致
- 变量初始化:所有变量必须初始化
- 边界检查:数组/容器访问前必须进行边界检查
- 空指针检查:指针解引用前必须进行空指针检查
- 返回值检查:关键函数必须检查返回值
Framework Specifications
框架规范
HWTEST_F Framework
HWTEST_F框架
cpp
// Test fixture structure
class YourServiceTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
std::shared_ptr<YourService> instance_;
};
// Test case format
HWTEST_F(TestClassName, TestCaseName_001, TestSize.Level1)cpp
// Test fixture structure
class YourServiceTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
std::shared_ptr<YourService> instance_;
};
// Test case format
HWTEST_F(TestClassName, TestCaseName_001, TestSize.Level1)Test Case Naming
测试用例命名
- : Normal scenario
_001 - : Exception scenario
_002 - : Boundary scenario
_003 - : Other special scenarios
_004+
- :正常场景
_001 - :异常场景
_002 - :边界场景
_003 - :其他特殊场景
_004+
Object Management
对象管理
cpp
// Standard smart pointers
SetUp(): instance_ = std::make_shared<YourService>();
TearDown(): instance_ = nullptr;
// OpenHarmony sptr/wptr
SetUp(): instance_ = MakeSptr<YourService>(); // or instance_ = new YourService();
TearDown(): instance_ = nullptr;cpp
// Standard smart pointers
SetUp(): instance_ = std::make_shared<YourService>();
TearDown(): instance_ = nullptr;
// OpenHarmony sptr/wptr
SetUp(): instance_ = MakeSptr<YourService>(); // or instance_ = new YourService();
TearDown(): instance_ = nullptr;Mock Usage
Mock使用示例
cpp
auto mock = std::make_shared<MockClass>();
EXPECT_CALL(*mock, Method()).WillOnce(Return(value));cpp
auto mock = std::make_shared<MockClass>();
EXPECT_CALL(*mock, Method()).WillOnce(Return(value));Assertions
断言示例
cpp
ASSERT_NE(instance_, nullptr); // Must check
EXPECT_EQ(result, expected);
EXPECT_TRUE(condition);cpp
ASSERT_NE(instance_, nullptr); // Must check
EXPECT_EQ(result, expected);
EXPECT_TRUE(condition);NDK Interface Testing
NDK接口测试
For NDK interfaces (OH_xxx), follow these requirements:
- Resource Lifecycle: Create/Destroy pairing is mandatory
- Test Structure: Normal path (001), Exception path (002), Boundary (003)
- Return Value Verification: Test all error codes
- Parameter Validation: Test null pointers, invalid values, boundaries
对于NDK接口(OH_xxx),需遵循以下要求:
- 资源生命周期:必须成对使用创建/销毁操作
- 测试结构:包含正常路径(001)、异常路径(002)、边界场景(003)
- 返回值验证:测试所有错误码
- 参数验证:测试空指针、无效值、边界值
CJSON Testing
CJSON测试
For CJSON library operations:
- Parse Tests: Normal, null pointer, invalid JSON
- Get Item Tests: Normal get, non-existent item, type checks
- Create Tests: Object, array, value creation
- Memory Management: All cJSON objects must be deleted
对于CJSON库操作:
- 解析测试:正常解析、空指针、无效JSON
- 获取项测试:正常获取、不存在项、类型检查
- 创建测试:对象、数组、值的创建
- 内存管理:所有cJSON对象必须被销毁
BUILD.gn Requirements
BUILD.gn要求
ohos_unittest Target
ohos_unittest目标
gn
ohos_unittest("{CamelCase}Test") {
module_out_path = "subsystem/module"
branch_protector_ret = "pac_ret"
sanitize = {
integer_overflow = true
cfi = true
cfi_cross_dso = true
debug = false
}
sources = ["test_file.cpp"] # Alphabetically sorted
include_dirs = ["//include/path"]
deps = [":source_target"]
external_deps = [
"hilog:libhilog",
"c_utils:utils",
"googletest:gtest_main"
]
defines = ["private=public"]
}gn
ohos_unittest("{CamelCase}Test") {
module_out_path = "subsystem/module"
branch_protector_ret = "pac_ret"
sanitize = {
integer_overflow = true
cfi = true
cfi_cross_dso = true
debug = false
}
sources = ["test_file.cpp"] # Alphabetically sorted
include_dirs = ["//include/path"]
deps = [":source_target"]
external_deps = [
"hilog:libhilog",
"c_utils:utils",
"googletest:gtest_main"
]
defines = ["private=public"]
}Configuration Matching
配置匹配
The system automatically extracts source file's BUILD.gn configuration:
- deps: Must include all source target dependencies
- external_deps: Must include all external dependencies
- include_dirs: Must include all include directories
- defines: Must match source defines (add private=public if needed)
系统会自动提取源文件的BUILD.gn配置:
- deps:必须包含所有源目标依赖
- external_deps:必须包含所有外部依赖
- include_dirs:必须包含所有头文件目录
- defines:必须与源文件的定义匹配(必要时添加private=public)
Reference Files
参考文件
Detailed specifications are available in the directory:
references/- framework-specs.md: HWTEST_F framework conventions and test patterns
- mock-strategies.md: Mock object creation and usage strategies
- coverage-requirements.md: Coverage metrics and optimization strategies
- build-gn-rules.md: BUILD.gn configuration and dependency matching
- assertion-standards.md: Assertion methods and branch correspondence
- code-style-consistency.md: Consistency requirements with existing tests
- smart-pointer-usage.md: sptr/wptr vs standard smart pointer usage
- ndk-napi-testing.md: NDK/NAPI interface testing specifications
- cjson-testing.md: CJSON library testing patterns
- security-coding.md: Memory management and secure coding requirements
详细规范可在目录中查看:
references/- framework-specs.md:HWTEST_F框架规范及测试模式
- mock-strategies.md:Mock对象创建及使用策略
- coverage-requirements.md:覆盖率指标及优化策略
- build-gn-rules.md:BUILD.gn配置及依赖匹配规则
- assertion-standards.md:断言方法及分支对应要求
- code-style-consistency.md:与现有测试的一致性要求
- smart-pointer-usage.md:sptr/wptr与标准智能指针的使用规范
- ndk-napi-testing.md:NDK/NAPI接口测试规范
- cjson-testing.md:CJSON库测试模式
- security-coding.md:内存管理及安全编码要求
Examples
示例
See the directory for:
examples/- basic-test-example.cpp: Basic test structure and patterns
- mock-test-example.cpp: Mock object usage examples
- ndk-test-example.cpp: NDK interface testing examples
可在目录中查看以下示例:
examples/- basic-test-example.cpp:基础测试结构及模式
- mock-test-example.cpp:Mock对象使用示例
- ndk-test-example.cpp:NDK接口测试示例