demo准备
假设在Android源码的system/security目录下有个hello工程,工程代码结构如下:
system/security$ ls -R hello/
hello/:
Android.bp src
hello/src:
hello.c hello.h main.c
Android.bp是makefile,src是源码文件。
hello.c中只实现了一个测试函数,代码如下:
int func_echo(int d) {
return d;
}
hello.h代码如下:
#ifdef __cplusplus
extern "C"{
#endif
int func_echo(int d);
#ifdef __cplusplus
}
#endif
main.c代码如下:
#include "hello.h"
int main() {
func_echo(1);
return 0;
}
编写单元测试代码
我们想对hello.h中定义hello.c中实现的func_echo函数做单元测试。
先在与src统计目录下创建tests目录,然后在tests目录中编写测试用例:
system/security$ ls -R hello/
hello/:
Android.bp src tests
hello/src:
hello.c hello.h main.c
hello/tests:
gtest_main.cpp some_test.cpp
gtest_main.cpp的内容是固定的,源码如下:
#include <gtest/gtest.h>
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
some_test.cpp中的多个测试用例:
#include <gtest/gtest.h>
#include "../src/hello.h"
TEST(Testfunc_echo, ZeroInput)
{
EXPECT_EQ(0, func_echo(0));
}
TEST(Testfunc_echo, NonZeroInput)
{
EXPECT_EQ(1, func_echo(1));
}
TEST(Testfunc_echo, Expect_Fail)
{
EXPECT_EQ(10, func_echo(100));
}
分三种情况对func_echo函数做测试。
Testfunc_echo宏的func_echo部分是被测函数,ZeroInput/NonZeroInput/Expect_Fail是测试描述。
Makefile
在Android.bp中添加测试用例编译配置:
cc_binary {
name: "hello",
srcs: [
"src/hello.c",
"src/main.c",
],
}
// Unit test for hello
cc_test {
cflags: [
"-Wall",
"-Werror",
"-Wextra",
"-O0",
],
ldflags : [
],
srcs: [
"tests/some_test.cpp",
"tests/gtest_main.cpp",
"src/hello.c"
],
name: "hello_tests",
static_libs: [
],
shared_libs: [
],
sanitize: {
cfi: false,
}
}
其中cc_test部分是用来编译测试用例的。
编译
在Android源码的根目录下执行mmm命令:
$ mmm system/security/hello -j4
[100% 356/356] Install: out/target/product/bengal/data/nativetest64/hello_tests/hello_tests
运行测试用例
# push到设备中
$ adb push out/target/product/bengal/data/nativetest64/hello_tests/hello_tests /data/nativetest64/hello_tests/hello_tests
out/target/product/bengal/data/nativetest64/hello_tests/h...o_tests: 1 file pushed. 5.0 MB/s (228536 bytes in 0.043s)
# 运行
$ adb shell /data/nativetest64/hello_tests/hello_tests
[==========] Running 3 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 3 tests from Testfunc_echo
[ RUN ] Testfunc_echo.ZeroInput
[ OK ] Testfunc_echo.ZeroInput (0 ms)
[ RUN ] Testfunc_echo.NonZeroInput
[ OK ] Testfunc_echo.NonZeroInput (0 ms)
[ RUN ] Testfunc_echo.Expect_Fail
system/security/hello/tests/some_test.cpp:17: Failure
Expected equality of these values:
10
func_echo(100)
Which is: 100
[ FAILED ] Testfunc_echo.Expect_Fail (0 ms)
[----------] 3 tests from Testfunc_echo (1 ms total)
[----------] Global test environment tear-down
[==========] 3 tests from 1 test suite ran. (1 ms total)
[ PASSED ] 2 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] Testfunc_echo.Expect_Fail
1 FAILED TEST
通过用例执行时的输入,可以知道some_test.cpp的17行调用func_echo函数时,预期返回10,但实际返回了100.
网友评论