gtest入门Primer(入门)

gtest 教程和gooletest入门教程、Primer(入门)

Basic Assertions

These assertions do basic true/false condition testing.

Fatal assertion Nonfatal assertion Verifies
ASSERT_TRUE(condition); EXPECT_TRUE(condition); condition is true
ASSERT_FALSE(condition); EXPECT_FALSE(condition); condition is false

Remember, when they fail, ASSERT_* yields a fatal failure and
returns from the current function, while EXPECT_* yields a nonfatal
failure, allowing the function to continue running. In either case, an
assertion failure means its containing test fails.

Availability: Linux, Windows, Mac.

Binary Comparison

This section describes assertions that compare two values.

Fatal assertion Nonfatal assertion Verifies
ASSERT_EQ(val1,val2); EXPECT_EQ(val1,val2); val1 == val2
ASSERT_NE(val1,val2); EXPECT_NE(val1,val2); val1 != val2
ASSERT_LT(val1,val2); EXPECT_LT(val1,val2); val1 < val2
ASSERT_LE(val1,val2); EXPECT_LE(val1,val2); val1 <= val2
ASSERT_GT(val1,val2); EXPECT_GT(val1,val2); val1 > val2
ASSERT_GE(val1,val2); EXPECT_GE(val1,val2); val1 >= val2

In the event of a failure, Google Test prints both val1 and val2.

String Comparison

The assertions in this group compare two C strings. If you want to compare
two string objects, use EXPECT_EQ, EXPECT_NE, and etc instead.

Fatal assertion Nonfatal assertion Verifies
ASSERT_STREQ(str1,str2); EXPECT_STREQ(str1,_str_2); the two C strings have the same content
ASSERT_STRNE(str1,str2); EXPECT_STRNE(str1,str2); the two C strings have different content
ASSERT_STRCASEEQ(str1,str2); EXPECT_STRCASEEQ(str1,str2); the two C strings have the same content, ignoring case
ASSERT_STRCASENE(str1,str2); EXPECT_STRCASENE(str1,str2); the two C strings have different content, ignoring case

Simple Tests

To create a test:

  1. Use the TEST() macro to define and name a test function, These are ordinary C++ functions that don’t return a value.
  2. In this function, along with any valid C++ statements you want to include, use the various Google Test assertions to check values.
  3. The test’s result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds.
  1. TEST(test_case_name, test_name) {
  2. ... test body ...
  3. }

A test case for this function might look like:

  1. // Tests factorial of 0.
  2. TEST(FactorialTest, HandlesZeroInput) {
  3. EXPECT_EQ(1, Factorial(0));
  4. }
  5. // Tests factorial of positive numbers.
  6. TEST(FactorialTest, HandlesPositiveInput) {
  7. EXPECT_EQ(1, Factorial(1));
  8. EXPECT_EQ(2, Factorial(2));
  9. EXPECT_EQ(6, Factorial(3));
  10. EXPECT_EQ(40320, Factorial(8));
  11. }

Test Fixtures: Using the Same Data Configuration for Multiple Tests

As an example, let’s write tests for a FIFO queue class named Queue, which
has the following interface:

  1. template <typename E> // E is the element type.
  2. class Queue {
  3. public:
  4. Queue();
  5. void Enqueue(const E& element);
  6. E* Dequeue(); // Returns NULL if the queue is empty.
  7. size_t size() const;
  8. ...
  9. };

First, define a fixture class. By convention, you should give it the name
FooTest where Foo is the class being tested.

  1. class QueueTest : public ::testing::Test {
  2. protected:
  3. virtual void SetUp() {
  4. q1_.Enqueue(1);
  5. q2_.Enqueue(2);
  6. q2_.Enqueue(3);
  7. }
  8. // virtual void TearDown() {}
  9. Queue<int> q0_;
  10. Queue<int> q1_;
  11. Queue<int> q2_;
  12. };

In this case, TearDown() is not needed since we don’t have to clean up after
each test, other than what’s already done by the destructor.

Now we’ll write tests using TEST_F() and this fixture.

  1. TEST_F(QueueTest, IsEmptyInitially) {
  2. EXPECT_EQ(0, q0_.size());
  3. }
  4. TEST_F(QueueTest, DequeueWorks) {
  5. int* n = q0_.Dequeue();
  6. EXPECT_EQ(NULL, n);
  7. n = q1_.Dequeue();
  8. ASSERT_TRUE(n != NULL);
  9. EXPECT_EQ(1, *n);
  10. EXPECT_EQ(0, q1_.size());
  11. delete n;
  12. n = q2_.Dequeue();
  13. ASSERT_TRUE(n != NULL);
  14. EXPECT_EQ(2, *n);
  15. EXPECT_EQ(1, q2_.size());
  16. delete n;
  17. }

Invoking the Tests

TEST() and TEST_F() implicitly register their tests with Google Test. So, unlike with many other C++ testing frameworks, you don’t have to re-list all your defined tests in order to run them.

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.

When invoked, the RUN_ALL_TESTS() macro:

  1. Saves the state of all Google Test flags.
  2. Creates a test fixture object for the first test.
  3. Initializes it via SetUp().
  4. Runs the test on the fixture object.
  5. Cleans up the fixture via TearDown().
  6. Deletes the fixture.
  7. Restores the state of all Google Test flags.
  8. Repeats the above steps for the next test, until all tests have run.

In addition, if the text fixture’s constructor generates a fatal failure in
step 2, there is no point for step 3 - 5 and they are thus skipped. Similarly,
if step 3 generates a fatal failure, step 4 will be skipped.

Important: You must not ignore the return value of RUN_ALL_TESTS(), or gcc
will give you 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 your main() function must
return the value of RUN_ALL_TESTS().

Also, you should call RUN_ALL_TESTS() only once. Calling it more than once
conflicts with some advanced Google Test features (e.g. thread-safe death
tests) and thus is not supported.

Writing the main() Function

You can start from this boilerplate:

  1. #include "this/package/foo.h"
  2. #include "gtest/gtest.h"
  3. namespace {
  4. // The fixture for testing class Foo.
  5. class FooTest : public ::testing::Test {
  6. protected:
  7. // You can remove any or all of the following functions if its body
  8. // is empty.
  9. FooTest() {
  10. // You can do set-up work for each test here.
  11. }
  12. virtual ~FooTest() {
  13. // You can do clean-up work that doesn't throw exceptions here.
  14. }
  15. // If the constructor and destructor are not enough for setting up
  16. // and cleaning up each test, you can define the following methods:
  17. virtual void SetUp() {
  18. // Code here will be called immediately after the constructor (right
  19. // before each test).
  20. }
  21. virtual void TearDown() {
  22. // Code here will be called immediately after each test (right
  23. // before the destructor).
  24. }
  25. // Objects declared here can be used by all tests in the test case for Foo.
  26. };
  27. // Tests that the Foo::Bar() method does Abc.
  28. TEST_F(FooTest, MethodBarDoesAbc) {
  29. const string input_filepath = "this/package/testdata/myinputfile.dat";
  30. const string output_filepath = "this/package/testdata/myoutputfile.dat";
  31. Foo f;
  32. EXPECT_EQ(0, f.Bar(input_filepath, output_filepath));
  33. }
  34. // Tests that Foo does Xyz.
  35. TEST_F(FooTest, DoesXyz) {
  36. // Exercises the Xyz feature of Foo.
  37. }
  38. } // namespace
  39. int main(int argc, char **argv) {
  40. ::testing::InitGoogleTest(&argc, argv);
  41. return RUN_ALL_TESTS();
  42. }

The ::testing::InitGoogleTest() function parses the command line for Google
Test flags, and removes all recognized flags. This allows the user to control a
test program’s behavior via various flags, which we’ll cover in AdvancedGuide.
You must call this function before calling RUN_ALL_TESTS(), or the flags
won’t be properly initialized.

On Windows, InitGoogleTest() also works with wide strings, so it can be used
in programs compiled in UNICODE mode as well.

But maybe you think that writing all those main() functions is too much work? We agree with you completely and that’s why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with gtest_main library and you are good to go.





posted @ 2016-08-30 19:41  -刀狂剑痴-  阅读(723)  评论(0编辑  收藏  举报