使用TEST CASE
TEST() and TEST_F() implicitly register their tests with googletest. So, unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them.
TEST()和TEST_F() 用GoogleTest隐式注册它们的测试。因此,与许多其他C++测试框架不同,您不必重新列出所有定义的测试以便运行它们。
After defining your tests, you can run them with RUN_ALL_TESTS() , which returns 0 if all the tests are successful, or 1 otherwise. Note that RUN_ALL_TESTS() runs all tests in your link unit -- they can be from different test cases, or even different source files.
定义测试后,可以使用RUN_ALL_TESTS() 运行它们,如果所有测试都成功,则返回0,否则返回1。
请注意,RUN_ALL_TESTS() 运行链接单元中的所有测试——它们可以来自不同的测试用例,甚至是不同的源文件。
When invoked, the RUN_ALL_TESTS() macro:
当使用RUN_ALL_TESTS() 时, 以下过程会被执行:
-
Saves the state of all googletest flags
保存所有GoogleTest标志的状态 -
Creates a test fixture object for the first test.
为第一个测试创建测试设备对象。 -
Initializes it via SetUp().
通过Setup()初始化它。 -
Runs the test on the fixture object.
在fixture对象上运行测试。 -
Cleans up the fixture via TearDown().
通过TearDown()清理fixture。 -
Deletes the fixture.
删除fixture。 -
Restores the state of all googletest flags
恢复所有GoogleTest标志的状态 -
Repeats the above steps for the next test, until all tests have run.
为下一个测试重复上述步骤,直到所有测试都运行完毕。
IMPORTANT: You must not ignore the return value of
RUN_ALL_TESTS()
, or you will get a compiler error. The rationale for this design is that the automated testing service determines whether a test has passed based on its exit code, not on its stdout/stderr output; thus yourmain()
function must return the value ofRUN_ALL_TESTS()
.
Also, you should callRUN_ALL_TESTS()
only once. Calling it more than once conflicts with some advanced googletest features (e.g. thread-safe death tests) and thus is not supported.
注意:RUN_ALL_TESTS()返回值不能被忽略,而且使用过程中只能被调用一次。
当然在使用RUN_ALL_TESTS()之前要进行初始化操作。
testing::InitGoogleTest(&argc, argv);
android代码实例
工程路径为:
androidCode/test/gtest_add
androidCode为源码根目录。
test.cpp:
#include "stdio.h"
#include "gtest/gtest.h"
int add_sum(int a, int b)
{
return a + b;
}
TEST(addsumTest, OneAddZeroInput) {
EXPECT_EQ(add_sum(1,0), 1);
}
TEST(addsumTest, addSomeInput) {
EXPECT_EQ(add_sum(1, 0), 1);
EXPECT_EQ(add_sum(2, 0), 2);
EXPECT_EQ(add_sum(3, 3), 6);
EXPECT_EQ(add_sum(8, 1024), 40320);
}
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
Android.mk:
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES := \
test.cpp
LOCAL_CFLAGS := \
-Wall
LOCAL_C_INCLUDES := \
$(LOCAL_PATH)/../../external/googletest/googletest/include
LOCAL_STATIC_LIBRARIES += libgtest libgtest_main
LOCAL_CLANG_CFLAGS += -Wno-error=unused-lambda-capture
LOCAL_MODULE:= bymanbu_test
include $(BUILD_EXECUTABLE)
include $(call all-makefiles-under, $(LOCAL_PATH))
编译
进入源码的根路径:
$ source build/envsetup.sh
$ lunch aosp_arm64-eng
image.png
将工程添加到test/
下。
执行mma
编译:
OK,大功告成,可以放到真机上去运行了,不过是native层,需要使用adb。O(∩_∩)O哈哈~
网友评论