Unit testing series – Test with Stub (Part 4)

The second szenario is using a stub.


Stub

#pragma once
#include "WindowManager.hpp"

class WindowManagerStub : public IWindowManager
{
public:
  bool drawAt(unsigned startX, unsigned endX,
              unsigned startY, unsigned endY) override;
};
#include "WindowManagerStub.hpp"

bool WindowManagerStub::drawAt(unsigned startX, unsigned endX,
                               unsigned startY, unsigned endY)
{
  return true;
}

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 "WindowManagerStub.hpp"

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

void UserInterfaceTest::TearDown() {}

TEST_F(UserInterfaceTest, loadWindow)
{
  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 WindowManagerStub.cpp Main.Test.cpp libwnd.a -lpthread -lgtest
$ ./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 (0 ms total)

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