Unit testing series – Test with Mock (Part 5)

The third szenario is using a mock.


Mock

#pragma once
#include "WindowManager.hpp"
#include <gmock/gmock.h>

class WindowManagerMock : public IWindowManager
{
public:
  MOCK_METHOD4(drawAt, bool(unsigned startX, unsigned endX,
                            unsigned startY, unsigned endY));
};


Test

#pragma once
#include "WindowManager.hpp"
#include "UserInterface.hpp"
#include <gtest/gtest.h>
#include <memory>

class UserInterfaceTest : public testing::Test
{
protected:
  virtual void SetUp();
  virtual void TearDown();
  std::shared_ptr<IWindowManager> m_windowMgr;
  std::unique_ptr<UserInterface> m_userInter;
};
#include "UserInterfaceTest.hpp"
#include "WindowManagerMock.hpp"

void UserInterfaceTest::SetUp()
{
  m_windowMgr.reset(new WindowManagerMock());
  m_userInter.reset(new UserInterface(m_windowMgr));
}

void UserInterfaceTest::TearDown() {}

TEST_F(UserInterfaceTest, loadWindow)
{
  std::shared_ptr<WindowManagerMock> windowMgrMock
    = std::dynamic_pointer_cast<WindowManagerMock>(m_windowMgr);
  ASSERT_NE(windowMgrMock, nullptr);

  using namespace testing;
  EXPECT_CALL(*windowMgrMock, drawAt(_,_,_,_)).WillRepeatedly(Return(true));
  bool done = m_userInter->loadWindow(0, 100, 0, 100);
  EXPECT_EQ(done, true);
}

App

#include <gtest/gtest.h>

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

Exec

$ g++ -c UserInterface.cpp WindowManager.cpp
$ ar rcs libwnd.a UserInterface.o WindowManager.o
$ g++ UserInterfaceTest.cpp Main.Test.cpp libwnd.a -lpthread -lgtest -lgmock
$ ./a.out 
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from UserInterfaceTest
[ RUN      ] UserInterfaceTest.loadWindow
[       OK ] UserInterfaceTest.loadWindow (0 ms)
[----------] 1 test from UserInterfaceTest (1 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[  PASSED  ] 1 test.