Study: Software(SW)/SW: Opensource

[OpenSource 사용하기] googleMock(gMock): C++ Mocking Library for googletest

DrawingProcess 2022. 7. 16. 16:40
반응형
본 문서는 'OpenSource 뜯어보기'라는 프로젝트의 일환으로.
Googlemock라는 googletest를 위한 Mocking Framework를 설치, 실행 등 사용하는 방법과 더불어, library 내 구조, 소스 분석 및 패턴 분석까지 다룰 예정이니 해당 오픈소스에 관심이 있다면 봐두길 권장합니다.
추가로, 일전에 [OpenSource 사용하기] Googletest(gtest): test library라는 googletest library를 설치, 실행 등 사용하는 방법에 대해 다룬 적이 있습니다. 이글을 읽고 googletest에 대해 알고 읽으시길 권장 드립니다.

1. 오픈소스의 목적

1.1 'GoogleMock(gMock): Mocking Library'에 대하여.

  • Mocking: unit tests를 작성할 때는 외부 디펜던시를 차단하고 테스트해야 하기에 외부에서 주입받은 클래스를 가짜로 만드는 것입니다.
  • Google Mock: Google's framework for writing and using C++ mock classes. It can help you derive better designs of your system and write better tests.
  • Fake vs Mocks
    • Fake: Fake objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake.
    • Mocks: objects pre-programmed with expectations, which form a specification of the calls they are expected to receive.

1.2 'GoogleMock(gMock): Mocking Library'의 장점

  • Provides a declarative syntax for defining mocks.
  • Can define partial (hybrid) mocks, which are a cross of real and mock objects.
  • Handles functions of arbitrary types and overloaded functions.
  • Comes with a rich set of matchers for validating function arguments.
  • Uses an intuitive syntax for controlling the behavior of a mock.
  • Does automatic verification of expectations (no record-and-replay needed).
  • Allows arbitrary (partial) ordering constraints on function calls to be expressed.
  • Lets a user extend it by defining new matchers and actions.
  • Does not use exceptions.
  • Is easy to learn and use.

1.3 'GoogleMock(gMock): Mocking Framework' 추가 정보

2. 환경 구축

2.1 using CMake (FetchContent)

# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 14)

message(STATUS "Fetching googletest...")
FetchContent_Declare(
  googletest
  GIT_REPOSITORY https://github.com/google/googletest.git
  GIT_TAG        release-1.10.0 # GCC 5.0 미만을 사용하는 경우 is_trivially_copy_constructible 지원이 되지 않으므로 1.11.0 이후는 사용 불가
)
set(gtest_build_tests OFF CACHE BOOL "Enable gtest tests" FORCE)
FetchContent_MakeAvailable(googletest)

target_sources(${PROJECT_NAME}_test PRIVATE gtest/<TestSourceCode>)
add_executable(${PROJECT_NAME}_test gtest/test_main.cpp)
add_test(NAME ${PROJECT_NAME}Test COMMAND ${PROJECT_NAME}_test)
target_link_libraries(${PROJECT_NAME}_test
    PRIVATE
      gtest ${PROJECT_NAME}
  )

2.2 간단한 사용 (Basic)

 

test_main.cpp

#include <gtest/gtest.h>
int main(int argc, char *argv[])
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
  • main() function must return the value of RUN_ALL_TESTS().
    • you should call RUN_ALL_TESTS() only once.
  • NOTE: ParseGUnitFlags() is deprecated in favor of InitGoogleTest().

TEST() module 

$ cd build/

// 해당 테스트 전체 실행
$ ./bin/module_test
$ ./bin/module_test --gtest_filter=<TestSuiteName>.*

// 해당 테스트 중 일부 테스트케이스 실행
$ ./bin/module_test --gtest_filter=<TestSuiteName>.<TestName>

3. 오픈소스 사용하기

Assertion

googletest를 입문할 때 대체로 조건의 참/거짓을 판단하는 assertion을 사용하며 입문합니다. 이는 결과를 success, nonfatal failure, or fatal failure로 반환하며, fatal failure이 발생하면 현재 함수를 중단합니다.

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;
}
  • ASSERT_* : 실패할 때 fatal failure를 생성 하고 현재 기능을 중단합니다 . 
    • Heap check와 같이 테스트를 실패할 때 계속하는 것이 합리적이지 않은 경우 사용합니다.
  • EXPECT_* : 현재 기능을 중단하지 않는 nonfatal failure를 생성합니다. 
    • 둘 이상의 실패를 보고할 수 있으므로 일반적으로 선호됩니다. 
  • You can check Boolean conditions, compare values based on relational operators, verify string values, floating-point values, and much more.

참고

반응형