DrawingProcess
드프 DrawingProcess
DrawingProcess
전체 방문자
오늘
어제
«   2025/06   »
일 월 화 수 목 금 토
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
  • 분류 전체보기 (968)
    • Profile & Branding (25)
      • Career (18)
    • IT Trends (254)
      • Conference, Faire (Experien.. (31)
      • News (187)
      • Youtube (19)
      • TED (8)
      • Web Page (2)
      • IT: Etc... (6)
    • Contents (98)
      • Book (67)
      • Lecture (31)
    • Project Process (94)
      • Ideation (0)
      • Study Report (34)
      • Challenge & Award (22)
      • 1Day1Process (5)
      • Making (5)
      • KRC-FTC (Team TC(5031, 5048.. (10)
      • GCP (GlobalCitizenProject) (15)
    • Study: ComputerScience(CS) (72)
      • CS: Basic (9)
      • CS: Database(SQL) (5)
      • CS: Network (14)
      • CS: OperatingSystem (3)
      • CS: Linux (39)
      • CS: Etc... (2)
    • Study: Software(SW) (95)
      • SW: Language (29)
      • SW: Algorithms (1)
      • SW: DataStructure & DesignP.. (1)
      • SW: Opensource (15)
      • SW: Error Bug Fix (43)
      • SW: Etc... (6)
    • Study: Artificial Intellige.. (149)
      • AI: Research (1)
      • AI: 2D Vision(Det, Seg, Tra.. (35)
      • AI: 3D Vision (70)
      • AI: MultiModal (3)
      • AI: SLAM (0)
      • AI: Light Weight(LW) (3)
      • AI: Data Pipeline (7)
      • AI: Machine Learning(ML) (1)
    • Study: Robotics(Robot) (33)
      • Robot: ROS(Robot Operating .. (9)
      • Robot: Positioning (8)
      • Robot: Planning & Control (7)
    • Study: DeveloperTools(DevTo.. (83)
      • DevTool: Git (12)
      • DevTool: CMake (13)
      • DevTool: NoSQL(Elastic, Mon.. (25)
      • DevTool: Container (17)
      • DevTool: IDE (11)
      • DevTool: CloudComputing (4)
    • 인생을 살면서 (64)
      • 나의 취미들 (7)
      • 나의 생각들 (42)
      • 여행을 떠나자~ (10)
      • 분기별 회고 (5)

개발자 명언

“ 매주 목요일마다 당신이 항상 하던대로 신발끈을 묶으면 신발이 폭발한다고 생각해보라.
컴퓨터를 사용할 때는 이런 일이 항상 일어나는데도 아무도 불평할 생각을 안 한다. ”

- Jef Raskin

맥의 아버지 - 애플컴퓨터의 매킨토시 프로젝트를 주도

인기 글

최근 글

최근 댓글

티스토리

hELLO · Designed By 정상우.
DrawingProcess

드프 DrawingProcess

Study: Software(SW)/SW: Opensource

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

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' 추가 정보

  • Git: https://github.com/google/googletest/blob/master/googlemock/README.md
  • Lisence: BSD 3-Clause "New" or "Revised" License: Copyright 2008, Google Inc.

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.
    • more info: see the Assertions Reference.

참고

  • [github] googletest: https://github.com/google/googletest
  • [github] googlemock: https://github.com/google/googletest/blob/master/googlemock/README.md
  • gMock for dummies: https://github.com/google/googletest/blob/master/googlemock/docs/for_dummies.md
  • gMock Cookbook: https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md
  • gMock Chear Sheet: https://github.com/google/googletest/blob/master/googlemock/docs/cheat_sheet.md
  • Legacy gMock FAQ : https://google.github.io/googletest/gmock_faq.html
  • C++ GoogleTest의 gMock 사용하여 유닛테스트 작성하기 (UnitTest): https://doll6777.github.io/c++/2020/05/20/gmock/
반응형
저작자표시 비영리 변경금지 (새창열림)

'Study: Software(SW) > SW: Opensource' 카테고리의 다른 글

[OpenSource 사용하기] fmt: C++ formatting library (feat. python styled print)  (2) 2022.08.18
[C++] C++ Json 라이브러리 변경: JsonCpp to Nlohmann/json...  (0) 2022.08.10
[OpenSource 사용하기] nlohmann/json: c++ json library (feat. Modern C++)  (0) 2022.07.05
[OpenSource 사용하기/뜯어보기] OpenSource 사용하기/뜯어보기 개요 및 목록  (0) 2022.06.29
[Opensource 뜯어보기] Opensource를 분석하는 이유?  (0) 2022.06.29
    'Study: Software(SW)/SW: Opensource' 카테고리의 다른 글
    • [OpenSource 사용하기] fmt: C++ formatting library (feat. python styled print)
    • [C++] C++ Json 라이브러리 변경: JsonCpp to Nlohmann/json...
    • [OpenSource 사용하기] nlohmann/json: c++ json library (feat. Modern C++)
    • [OpenSource 사용하기/뜯어보기] OpenSource 사용하기/뜯어보기 개요 및 목록
    DrawingProcess
    DrawingProcess
    과정을 그리자!

    티스토리툴바