I'm new to google mock and I'm trying to mock an interface, but keep getting a linker error with undefined symbols for architecture x86_64
Here's my simplified code:
I have the following in a .h file:
namespace Mynamespace
{
class IMyInterface
{
public:
virtual ~ IMyInterface() {};
virtual void myFunction() = 0;
};
}
this in another .h file:
#include <gmock/gmock.h>
#include <IMyInterface.h>
namespace testing
{
class MyClassMock : public IMyInterface
{
public:
~ MyClassMock();
MyClassMock(int, int, int);
MOCK_METHOD0(myFunction, void());
};
}
and this in my Test Case .cpp file:
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <IMyInterface.h>
namespace testing
{
TEST(MyClassMock, myFunction)
{
MyClassMock mcm(0,0,0);
}
}
Do you have an idea what am I doing wrong?
Any help would be very much appreciated!
cheers,
Simon
EDIT:
Unfortunately the mock still doesn't seem to work. After I added the implementation like this:
namespace testing
{
MyClassMock:: MyClassMock(int a, int b, int c)
{
}
MyClassMock::~ MyClassMock()
{
}
}
"myFunction" will not be called when I do
#include "MyClassMock.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using ::testing::AtLeast;
using namespace testing;
TEST(MyClassTest, canCallFunction)
{
MyClassMock mock(0,0,0);
EXPECT_CALL(mock, myFunction())
.Times(AtLeast(1));
}
returning:
EXPECT_CALL(mock, myFunction())
Expected: to be called at least once
Actual: never called - unsatisfied and active
You have to provide implementations for MyClassMock::MyClassMock(int, int, int) and MyClassMock::~MyClassMock().
On a side not, you should use "" rather than <> when you #include your own headers. E.g. #include "IMyInterface.h" not #include <IMyInterface.h>. That way, the compiler will search in the current directory prior to the system include path.
Related
I am trying to mock global function using https://github.com/apriorit/gmock-global library.
Note: this description contains example of the real scenario not the exact real scenario. Also I am not allowed to make any changes to global.hpp.
My example dir structure looks like below
--src
------global.hpp
------classA.hpp
------classB.hpp
------main.cpp
--ut
------classATests.cpp
------classBTests.cpp
------main.cpp
The ut/main.cpp tests testcases in classATests.cpp and classBTests.cpp.
global.hpp contains a global function
int giveIndex()
{
return 1;
}
classA.hpp calls giveIndex() global function
#include "global.hpp"
class A
{
public:
int checkIndex() { return giveIndex(); };
}
classB.hpp calls giveIndex() global function
#include "global.hpp"
class B
{
public:
int checkIndex() { return giveIndex(); };
}
classATests.cpp contains
#include <memory>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <gmock-global/gmock-global.h>
#include "src/classA.hpp"
MOCK_GLOBAL_FUNC0(giveIndex, int(void));
using namespace ::testing
struct classATests : public ::testing::Test
{
void Setup() override
{
sut_ = std::make_shared<A>();
}
std::shared_ptr<A> sut_;
};
TEST_F(classATests , checkIndex)
{
EXPECT_GLOBAL_CALL(giveIndex, giveIndex()).WillOnce(Return(1));
sut_->checkIndex();
}
classBTests.cpp contains
#include <memory>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <gmock-global/gmock-global.h>
#include "src/classB.hpp"
MOCK_GLOBAL_FUNC0(giveIndex, int(void));
using namespace ::testing
struct classBTests : public ::testing::Test
{
void Setup() override
{
sut_ = std::make_shared<B>();
}
std::shared_ptr<B> sut_;
};
TEST_F(classBTests , checkIndex)
{
EXPECT_GLOBAL_CALL(giveIndex, giveIndex()).WillOnce(Return(1));
sut_->checkIndex();
}
The issue now is when i compile and run UT for both classATests.cpp and classBTests.cpp i get errors saying
... multiple definition of 'giveIndex' ;
and
... multiple definitions of gmock_globalmock_giveIndex_instance
Is there any way to avoid this issue ? classA tests and classB tests need to be in 2 different files like it is now.
Functions defined in header files should be defined inline
inline int giveIndex()
{
return 1;
}
otherwise you will get multiple definition errors if you include the header file more than once.
The alternative would be to only declare the function in your header file
int giveIndex();
and then define it (but not inline) in one of your cpp files.
This is the normal way to organise C++ code. gmock has nothing to do with this.
I have a C++/WinRT base class that I need to subclass. My problem is that I don't manage to call the base class's protected constructor from the subclass.
That base class is defined in MIDL as follows:
namespace My.Custom.WindowsRuntimeComponent
{
unsealed runtimeclass BaseClass : Windows.UI.Xaml.Controls.SwapChainPanel
{
}
}
From it, the following header and implementation is created:
#pragma once
#include <DirectXMath.h>
#include "BaseClass.g.h"
namespace winrt::My::Custom::WindowsRuntimeComponent::implementation
{
struct BaseClass : BaseClassT<BaseClass>
{
protected:
BaseClass();
::DirectX::XMFLOAT3 ProtectedMethod();
};
}
#include "pch.h"
#include "BaseClass.h"
#include "BaseClass.g.cpp"
namespace winrt::My::Custom::WindowsRuntimeComponent::implementation
{
BaseClass::BaseClass()
{
// Important stuff happening here
}
::DirectX::XMFLOAT3 BaseClass::ProtectedMethod()
{
return ::DirectX::XMFLOAT3();
}
}
The subclass's MIDL, header and implementation are defined as follows:
import "BaseClass.idl";
namespace My.Custom.WindowsRuntimeComponent
{
runtimeclass SubClass : BaseClass
{
SubClass();
void UseProtectedMethod();
}
}
#pragma once
#include "BaseClass.h"
#include "SubClass.g.h"
namespace winrt::My::Custom::WindowsRuntimeComponent::implementation
{
struct SubClass : SubClassT<SubClass, My::Custom::WindowsRuntimeComponent::implementation::BaseClass>
{
SubClass();
void UseProtectedMethod();
};
}
namespace winrt::My::Custom::WindowsRuntimeComponent::factory_implementation
{
struct SubClass : SubClassT<SubClass, implementation::SubClass>
{
};
}
#include "pch.h"
#include "SubClass.h"
#include "SubClass.g.cpp"
namespace winrt::My::Custom::WindowsRuntimeComponent::implementation
{
SubClass::SubClass()
{
}
void SubClass::UseProtectedMethod()
{
::DirectX::XMFLOAT3 value = ProtectedMethod();
}
}
The above example compiles. However, if I attempt to call the protected base class constructor from the initializer list of the subclass as shown below I receive a compiler error.
#include "pch.h"
#include "SubClass.h"
#include "SubClass.g.cpp"
namespace winrt::My::Custom::WindowsRuntimeComponent::implementation
{
SubClass::SubClass() : BaseClass() // This line does not compile
{
}
void SubClass::UseProtectedMethod()
{
::DirectX::XMFLOAT3 value = ProtectedMethod();
}
}
The compiler error is as follows:
error C2614: 'winrt::My::Custom::WindowsRuntimeComponent::implementation::SubClass': illegal member initialization: 'BaseClass' is not a base or member
Both in the MIDL and the header of SubClass I specify that it inherits from BaseClass so it is unclear to me why the compiler emits that error.
I could work around that problem, I guess, but I'm curious about what exactly is going on here. Any hints?
The SubClass in the winrt::... namespace derives from SubClassT<...>, not from SubClass.
The SubClass that is outside the winrt:: namespace derives from BaseClass, but thats a different one. Your naming is easy to get lost in.
I'm writing some test cases for my C++ project using Microsoft::VisualStudio::CppUnitTestFramework. Here I have a case where I have to run a same test case with different parameters.
In Nunit Framework for CPP, I can achieve this by the following code.
[Test, SequentialAttribute]
void MyTest([Values("A", "B")] std::string s)
{
}
By passing these parameters, this test will run 2 times.
MyTest("A")
MyTest("B")
Is there a similar way to achieve this in Microsoft::VisualStudio::CppUnitTestFramework unit test.
Any help is highly appreciated.
The CppUnitTestFramework doesn't provide for parameterized tests, but there's nothing to prevent you from simply writing a parameterized function and calling it from your tests.
void MyTest(char *param)
{
// Actual test code here
}
TEST_METHOD(MyTest_ParamA)
{
MyTest("A");
}
TEST_METHOD(MyTest_ParamB)
{
MyTest("B");
}
I had a similar problem: I have an interface and several implementations of it. Of course I do only want to write tests against the interface. Also, I do not want to copy my tests for each implementation. Therefore, I searched for a way to pass parameters to my test. Well, my solution is not very pretty but it is straightforward and the only one I came up with until now.
Here is my solution for my problem (in your case CLASS_UNDER_TEST would be the parameter you want to pass into the test):
setup.cpp
#include "stdafx.h"
class VehicleInterface
{
public:
VehicleInterface();
virtual ~VehicleInterface();
virtual bool SetSpeed(int x) = 0;
};
class Car : public VehicleInterface {
public:
virtual bool SetSpeed(int x) {
return(true);
}
};
class Bike : public VehicleInterface {
public:
virtual bool SetSpeed(int x) {
return(true);
}
};
#define CLASS_UNDER_TEST Car
#include "unittest.cpp"
#undef CLASS_UNDER_TEST
#define CLASS_UNDER_TEST Bike
#include "unittest.cpp"
#undef CLASS_UNDER_TEST
unittest.cpp
#include "stdafx.h"
#include "CppUnitTest.h"
#define CONCAT2(a, b) a ## b
#define CONCAT(a, b) CONCAT2(a, b)
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
TEST_CLASS(CONCAT(CLASS_UNDER_TEST, Test))
{
public:
CLASS_UNDER_TEST vehicle;
TEST_METHOD(CONCAT(CLASS_UNDER_TEST, _SpeedTest))
{
Assert::IsTrue(vehicle.SetSpeed(42));
}
};
You will need to exclude „unittest.cpp“ from build.
Quick and simple solution:
Create a vector with your test cases in TEST_METHOD_INITIALIZE, then iterate over the vector in each test case.
#include "stdafx.h"
#include "CppUnitTest.h"
#include <vector>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace SomeTests
{
TEST_CLASS(Some_Tests)
{
public:
std::vector<int> myTestCases;
TEST_METHOD_INITIALIZE(Initialize_Test_Cases)
{
myTestCases.push_back(1);
myTestCases.push_back(2);
myTestCases.push_back(3);
}
TEST_METHOD(Test_GreaterThanZero)
{
for (auto const& testCase : myTestCases)
{
Assert::IsTrue(testCase > 0);
}
}
};
}
Below are by 4 classes, I'm learning about basic c++ syntax and boy is it much harder and less forgiving than other languages I have used. I have a main class, base class "BaseArray" and two sub classes "OrderedArray" and "UnorderedArray".
Main.cpp
#include <iostream>
#include "OrderedArray.cpp"
#include "UnorderedArray.cpp"
using namespace std;
int main() {
system("PAUSE");
return 0;
}
BaseArray.cpp
#include <iostream>
using namespace std;
class BaseArray {
public:
BaseArray::BaseArray() {
}
};
OrderedArray.cpp
#include <iostream>
#include "BaseArray.cpp"
using namespace std;
class OrderedArray : public BaseArray {
OrderedArray::OrderedArray() {
}
};
UnorderedArray.cpp
#include <iostream>
#include "BaseArray.cpp"
using namespace std;
class UnorderedArray : public BaseArray {
UnorderedArray::UnorderedArray() {
}
};
The errors I receive are as followed, from scouting other threads online. I think it might have to do with duplicate calling of classes. To be honest, I have no clue. If someone could point me in the right direction that would be nice, thanks in advance!
error C2011: 'BaseArray':'class' type redefinition
error C2504: 'BaseArray':base class undefined
To fix this error I can remove one of the includes at the top of main.cpp, but I need those to create objects and call functions from the subclasses later on.
You should put your base array in a header:
BaseArray.h
#ifndef BASEARRAY_H_GUARD // include guard
#define BASEARRAY_H_GUARD // include guard
// no using namespace !!
// only includes needed for what's in the header
class BaseArray {
public:
BaseArray();
};
#endif // include guard
And then leave in the cpp only the implementation part of your class:
BaseArray.cpp
#include <iostream>
#include "BaseArray.h"
using namespace std;
BaseArray::BaseArray() { // no need class enclosing: the BaseArray:: prefix is sufficient
}
The you can apply the same principle to the derived classes:
OrderedArray.h
#ifndef BASEARRAY_H_GUARD // include guard
#define BASEARRAY_H_GUARD // include guard
#include "BaseArray.h" // include only those that you need but all those that you need
class OrderedArray : public BaseArray { // requires BaseArray
OrderedArray();
};
#endif
OrderedArray.cpp
#include <iostream> // include headers that are needed for class implementation
#include "OrderedArray.h" // this should be self contained and provide
// evertyhing that is needed for the class itself
using namespace std;
OrderedArray::OrderedArray() {
}
You then have to do the same for UnorderedArray and finally, you have to adapt your main.cpp to include .h instead of .cpp. And you're done.
A final remark: your cpp source code files are now ready for separate compilation. This means that you can no longer compile only main.cpp, hoping that it includes all the code: you have now to compile the 4 cpp files and link them together.
I have a fairly simple situation, and the fact that I can't cope with it drives me crazy.
I have a class that is declared as follows:
// inc/Services/Specific/ReviewRetriever.h
#include "../../ReviewRetriever.h"
class Specific_ReviewRetriever : public ReviewRetriever
{
public:
Specific_ReviewRetriever(Service* service);
~Specific_ReviewRetriever() = default;
};
Implementation of the class goes as follows:
// src/Services/TrustedShops/ReviewRetriever.cpp
#include <string>
#include <vector>
#include "Service.h"
#include "Services/Specific/ReviewRetriever.h"
Specific_ReviewRetriever::Specific_ReviewRetriever(Service* service) :
ReviewRetriever(service)
{
}
std::string Specific_ReviewRetriever::prepare_update_link(std::string link)
{
}
std::vector<int> Specific_ReviewRetriever::parse_response(boost::property_tree::ptree responseXML)
{
}
This class inherits from the class that is declared as follows:
// inc/ReviewRetriever.h
#include <string>
#include <vector>
#include <boost/property_tree/ptree.hpp>
#include "Review.h"
class Service;
class ReviewRetriever
{
public:
~ReviewRetriever() = default;
void retrieve(std::vector<Review> & reviews);
protected:
ReviewRetriever(Service* service);
virtual std::string prepare_update_link(std::string link) = 0;
virtual std::vector<Review> parse_response(boost::property_tree::ptree responseXML) = 0;
Service* _service;
};
And this class on its part is defined as follows:
// src/ReviewRetriever.cpp
#include <vector>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include "Review.h"
#include "ReviewRetriever.h"
void ReviewRetriever::retrieve(std::vector<Review> & reviews)
{
}
So a fairly simple class and another one that inherits from it. But when I try to compile the code I get the following error:
no ‘std::string Specific_ReviewRetriever::prepare_update_link(std::string)’
member function declared in class ‘Specific_ReviewRetriever’
So, even though I got implementation of the class, the compiler doesn't seem to notice it (even though it sees that the class Specific_ReviewRetriever inherits from ReviewRetriever, it refuses to recognize its methods).
I build with cmake and here is the relevant part:
// src/CMakeLists.txt
file(GLOB_RECURSE sources *.cpp)
target_include_directories(my_target PRIVATE ${PROJECT_SOURCE_DIR}/inc/)
(here ${PROJECT_SOURCE_DIR} is src/../).
So as I mentioned, implementation and declaration of the classes is present, and yet compilation fails. I understand that the problem may not be on the surface, but I am really clueless where to start to track the error, maybe you have a piece of advice on that.
In case this excerpt of code is insufficient, entire code lies here.
Thank you in advance!
You still have to declare the functions that you're overriding in the derived class:
class Specific_ReviewRetriever : public ReviewRetriever
{
public:
Specific_ReviewRetriever(Service* service);
~Specific_ReviewRetriever() = default;
// Overrides:
virtual std::string prepare_update_link(std::string link);
virtual std::vector<int> Specific_ReviewRetriever::parse_response(boost::property_tree::ptree responseXML);
};