Google Test

규규·2024년 3월 27일
0

C++

목록 보기
17/21

용어 정리

  • Google test 에서의 Test Case :
    • 관련있는 tests 들의 group (일반적으로 많은 서적에서는 이 경우를 Test Suite 라고 표현 함. International Software Testing Qualifications Board (ISTQB) 에서도 Test Suite 라고 표현)
    • 최근 document 에서는 Google test 에서도 Test Suite 이라고 표현.
  • Google test 에서의 Test : 일반적인 특정 Test Case

Basic concepts

  • testassertions sentence 로 이루어져 있음.
  • test suite 은 여러 tests 로 구성. tests code 가 objects, subroutine 을 공용으로 사용한다면 text fixture class 로 넣어도 됨.
  • test program 은 여러개의 test suites 를 포함.

Assertions

  • GoogleTest assertions 은 funtion calls 와 유사한 macro 임.
  • function 이나 class 를 testing
  • assertion 은 다양한 영향(?) 끼칠 수 있음
    • ASSERT_* : fatal failure and abort the function
    • EXPECT_* : nonfatal failure. 일반적으로 선호 됨
  • 다양한 방법으로 code test 가능 (boolean, relational operators, verify string, floating-point)
  • Custom failure message 사용을 위해서 << operator 사용
    • ex:
ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";

for (int i = 0; i < x.size(); ++i) {
  EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
}

Simple Tests

TEST(TestSuiteName, TestName) {
  ... test body ...
}
  • ex :
// Tests factorial of 0.
TEST(FactorialTest, HandlesZeroInput) {
  EXPECT_EQ(Factorial(0), 1);
}

// Tests factorial of positive numbers.
TEST(FactorialTest, HandlesPositiveInput) {
  EXPECT_EQ(Factorial(1), 1);
  EXPECT_EQ(Factorial(2), 2);
  EXPECT_EQ(Factorial(3), 6);
  EXPECT_EQ(Factorial(8), 40320);
}

Test Fixtures

  • TEST() 대신 TEST_F() 를 사용.
  • TODO : 추가 정리...

Invoking the Tests

  • TEST() and TEST_F() implicitly register their tests with GoogleTest.
  • tests define 후, RUN_ALL_TESTS() 로 Run. tests 가 모두 성공이면 0, 아니면 1 return.
  • RUN_ALL_TESTS() 호출 시
    • Saves the state of all GoogleTest flags.
    • Creates a test fixture object for the first test.
    • Initializes it via SetUp().
    • Runs the test on the fixture object.
    • Cleans up the fixture via TearDown().
    • Deletes the fixture.
    • Restores the state of all GoogleTest flags.
    • Repeats the above steps for the next test, until all tests have run.
  • RUN_ALL_TESTS() 의 return 값을 무시하면 compile error 발생. Tets 성공 여부를 exit code 로 확인하기 때문에 main() funciton 은 반드시 RUN_ALL_TESTS() 값을 return 받아야 함.
  • RUN_ALL_TESTS() 는 한번만 호출해야 함.

Writing the main() Function

  • 대부분의 User 는 main function 을 작성 할 필요 없고 gtest_main, gtest 사용이면 되지만, test 수행 전에 fixture 나 test suite 으로 대응이 불가능하고 custom 하게 수행 해야 될 일이 있으면 main 작성 필요.
  • main 함수는 RUN_ALL_TESTS() 를 반드시 return 해야 함.
  • testing::InitGoogleTest() 함수는 GoogleTest flags 를 parsing 하고 삭제. RUN_ALL_TESTS() 실행 전에 반드시 calling 해야 flags 가 정상 작동 함.
  • main 함수이 과하면, gtest_main library 로 간단하게 테스트 진행 가능.
  • boilerpalte e.g.:
#include "this/package/foo.h"

#include <gtest/gtest.h>

namespace my {
namespace project {
namespace {

// The fixture for testing class Foo.
class FooTest : public testing::Test {
 protected:
  // You can remove any or all of the following functions if their bodies would
  // be empty.

  FooTest() {
     // You can do set-up work for each test here.
  }

  ~FooTest() override {
     // You can do clean-up work that doesn't throw exceptions here.
  }

  // If the constructor and destructor are not enough for setting up
  // and cleaning up each test, you can define the following methods:

  void SetUp() override {
     // Code here will be called immediately after the constructor (right
     // before each test).
  }

  void TearDown() override {
     // Code here will be called immediately after each test (right
     // before the destructor).
  }

  // Class members declared here can be used by all tests in the test suite
  // for Foo.
};

// Tests that the Foo::Bar() method does Abc.
TEST_F(FooTest, MethodBarDoesAbc) {
  const std::string input_filepath = "this/package/testdata/myinputfile.dat";
  const std::string output_filepath = "this/package/testdata/myoutputfile.dat";
  Foo f;
  EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0);
}

// Tests that Foo does Xyz.
TEST_F(FooTest, DoesXyz) {
  // Exercises the Xyz feature of Foo.
}

}  // namespace
}  // namespace project
}  // namespace my

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Googletest Samples

  • 링크 : https://github.com/google/googletest/blob/main/googletest/samples
  • Sample #1 shows the basic steps of using googletest to test C++ functions.
  • Sample #2 shows a more complex unit test for a class with multiple member functions.
  • Sample #3 uses a test fixture.
  • Sample #4 teaches you how to use googletest and googletest.h together to get the best of both libraries.
  • Sample #5 puts shared testing logic in a base test fixture, and reuses it in derived fixtures.
  • Sample #6 demonstrates type-parameterized tests.
  • Sample #7 teaches the basics of value-parameterized tests.
  • Sample #8 shows using Combine() in value-parameterized tests.
  • Sample #9 shows use of the listener API to modify Google Test’s console output and the use of its reflection API to inspect test results.
  • Sample #10 shows use of the listener API to implement a primitive memory leak checker.

gtest_main.cc 사용법

https://zidarn87.tistory.com/?page=2

출처:
Google test tutorial : https://google.github.io/googletest/primer.html

profile
복습용 저장소

0개의 댓글