← Back to list

Note to future self: How to use gmock/gtest in cpp unit tests

Basic overview of this is how to use gmock/gtest when writing cpp unit tests.

Sindy is BORED · 2025-01-31 20:09 · 0 claps · 1.1 min read
#cpp #mock #gtest
Open on Medium ↗

Note to future self: How to use gmock/gtest in cpp unit tests

Basic overview of this is how to use gmock/gtest when writing cpp unit tests.

Steps on how to use gmock/gtest.

Note: Assuming you have your project set, unit tests in cpp are compiled as executable files. They are in a separate project from your package in genera.

  1. Install gmock/gtest and configure it so that your project uses it. In particular, if you’re using premake and conan, get the package and use premake.lua files to set the paths for the gmock/gtest directories.
  2. Include gmock.h and gtest.h files in your test_script.cpp file.
  3. When writing tests, you can name each test kind of like a class. Basically do this: TEST(NameOfTest){//write your test} since TEST is a macro, you don’t have to define NameOfTest above or anything.
  4. So overall, the files should look something like this:
// IBaseClass.h

class IBaseClass {
  public:
    virtual int methodToMock(int param1) = 0;
    // note that setting this to 0 is important
    // if you use namespaces make sure this is also set correctly
}
// BaseClass.h
#include "IBaseClass.h"

class BaseClass : public IBaseClass{
  private:
    std::string privateVar1;
    std::string privateVar2; //whatever
  public:
    BaseClass();
    virtual int methodToMock(int param1) override;
}
// MockBaseClass.h
#include "IBaseClass.h"
#include <gmock/gmock.h>

class MockBaseClass : public IBaseClass{
  MOCK_METHOD(); // follow the method pattern you wanted to mock
}
//test_script.cpp
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "BaseClass.h"
#include "IBaseClass.h"
#include "MockBaseClass.h"

TEST(ExampleTest) {
  MockBaseClass mock;
  EXPECT_CALL(mock, methodToMock(123))
    .Times(1).WillRepeatedly(testing::Return(456)); //can also be on_call
  auto result = otherClass.methodThatCallsBaseMock(); // set this up before
  ASSERT_EQ(456, result);
}

When faced with errors, double check the following:

  • Is everything being included?
  • Does the mock assembly have access to the interface file?
  • Is every library linked correctly?

메타데이터
post_id
294ebe92f2f5
slug
note-to-future-self-how-to-use-gmock-gtest-in-cpp-unit-tests-294ebe92f2f5
url
https://medium.com/@seohyun.aum/note-to-future-self-how-to-use-gmock-gtest-in-cpp-unit-tests-294ebe92f2f5
canonical_url
https://medium.com/@seohyun.aum/note-to-future-self-how-to-use-gmock-gtest-in-cpp-unit-tests-294ebe92f2f5
author_url
https://medium.com/@seohyun.aum
status
ok
fetched_at
2026-06-26 12:24:55