I need to write the gtest to test some existing code that has a non-virtual method, hence I am testing using the below source, but I am getting the compilation error
package/web/webscr/sample_template_class3.cpp: In function âint main()â:
package/web/webscr/sample_template_class3.cpp:64: error: âclass Templatemyclassâ has no member named âgmock_displayâ
sample_template_class3.cpp
#include <iostream>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace std;
template < class myclass>
class Templatemyclass
{
private:
myclass T;
public :
void display()
{
T.display();
}
};
class Test
{
public:
void display()
{
cout<<"Inside the display Test:" <<endl;
}
};
class MockTest
{
public:
MOCK_METHOD0(display,void());
};
class FinalTest
{
public:
void show( Templatemyclass<Test> t)
{
t.display();
cout<<"Inside the display FinalTest:" <<endl;
}
};
int main()
{
FinalTest test1;
Templatemyclass<Test> obj1;
Templatemyclass<MockTest> obj2;
EXPECT_CALL(obj2,display()).Times(1);
test1.show(obj1);
return 1;
}
There are a couple of issues in your code. I have changed it below and commented the code by way of explanation. If this is not clear enough, add a comment and I'll try and explain further.
#include <iostream>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace std;
template <class myclass>
class Templatemyclass {
private:
// Hold a non-const ref or pointer to 'myclass' so that the actual
// object passed in the c'tor is used in 'display()'. If a copy is
// used instead, the mock expectations will not be met.
myclass* T;
public :
// Pass 'myclass' in the c'tor by non-const ref or pointer.
explicit Templatemyclass(myclass* t) : T(t) {}
void display() { T->display(); }
};
class Test {
public:
void display() { cout << "Inside the display Test:" << endl; }
};
class MockTest {
public:
MOCK_METHOD0(display, void());
};
class FinalTest {
public:
// Templatise this function so we can pass either a Templatemyclass<Test>
// or a Templatemyclass<MockTest>. Pass using non-const ref or pointer
// again so that the actual instance with the mock expectations set on it
// will be used, and not a copy of that object.
template<class T>
void show(T& t) {
t.display();
cout<<"Inside the display FinalTest:" <<endl;
}
};
int main() {
Test test;
Templatemyclass<Test> obj1(&test);
MockTest mock_test;
Templatemyclass<MockTest> obj2(&mock_test);
EXPECT_CALL(mock_test,display()).Times(1);
FinalTest test1;
test1.show(obj1);
test1.show(obj2);
return 0;
}
The following could possibly simplify the case:
#include <iostream>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
template <class myclass>
class Templatemyclass {
public:
myclass T;
void show() const { T.display(); }
};
struct Test {
void display() const { std::cout << "Inside the display Test:\n"; }
};
struct MockTest {
MOCK_CONST_METHOD0(display, void());
};
int main() {
Templatemyclass<Test> obj1;
obj1.show();
Templatemyclass<MockTest> obj2;
EXPECT_CALL(obj2.T, display()).Times(1);
obj2.show();
return 0;
}
If you don't want to change your source code, you can leverage injector++.
Currently it only supports x86 Windows. But Linux and x64 Windows support will come soon. Below examples will give you a brief idea:
Mock non-virtual methods
Below example fakes BaseClassTest::getAnInteger() by using fakeFunc():
class FakeClassNonVirtualMethodTestFixture : public ::testing::Test
{
public:
int fakeFunc()
{
return 6;
}
};
TEST_F(FakeClassNonVirtualMethodTestFixture, FakeIntFunctionWhenCalled)
{
// Prepare
int expected = 6;
InjectorPP::Injector injector;
injector.whenCalled(INJECTORPP_MEMBER_FUNCTION(BaseClassTest::getAnInteger))
.willExecute(INJECTORPP_MEMBER_FUNCTION(FakeClassNonVirtualMethodTestFixture::fakeFunc));
BaseClassTest b = BaseClassTest();
// Act
// FakeFunc will be executed!
int actual = b.getAnInteger();
// Assert
EXPECT_EQ(expected, actual);
}
Mock virtual methods
Injector++ supports virtual method mocking (Amazing, huh?). Below is a simple example:
int FakeIntFuncForDerived()
{
return 2;
}
TEST_F(FakeClassVirtualMethodTestFixture, MockDerivedClassVirtualMemberFunctionWhenCalled)
{
// Prepare
int expected = 2;
BaseClassTest* derived = new SubClassTest();
InjectorPP::Injector injector;
injector.whenCalledVirtualMethod(derived, "getAnIntegerVirtual")
.willExecute(fakeIntFuncForDerived);
// Act
// FakeIntFuncForDerived() will be exectued!
int actual = derived->getAnIntegerVirtual();
// Assert
EXPECT_EQ(expected, actual);
delete derived;
derived = NULL;
}
Mock static methods
Injector++ supports static method mocking. Below is a simple example:
Address FakeGetAnAddress()
{
Address addr;
addr.setAddressLine("fakeAddressLine");
addr.setZipCode("fakeZipCode");
return addr;
}
TEST_F(FakeClassNonVirtualMethodTestFixture, FakeStaticFunctionReturnUserDefinedClassWhenCalled)
{
// Prepare
Address expected;
expected.setAddressLine("fakeAddressLine");
expected.setZipCode("fakeZipCode");
InjectorPP::Injector injector;
injector.whenCalled(INJECTORPP_STATIC_MEMBER_FUNCTION(BaseClassTest::getAnAddressStatic))
.willExecute(INJECTORPP_MEMBER_FUNCTION(FakeClassNonVirtualMethodTestFixture::fakeGetAnAddress));
// Act
// FakeGetAnAddress will be executed!
Address actual = BaseClassTest::getAnAddressStatic();
// Assert
EXPECT_EQ(expected, actual);
}
Related
#include<iostream>
#include <thread>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
class base
{
public:
virtual void fun_1() { cout << "base-1\n"; }
virtual void fun_2() { cout << "base-2\n"; }
};
class derived : public base
{
public:
void fun_1() { cout << "derived-1\n"; }
void fun_2() { cout << "derived-2\n";
}
};
class caller
{
private:
base *p;
derived obj1;
p = &obj1;
public:
void me()
{
std::thread t(std::bind(&base::fun_2, p), this);
t.join();
}
};
int main()
{
caller c;
c.me();
return 0;
}
I have a written a very simple threading and polymorphism example. All I wanted to do is to call a derived function from a different class which is containing that another class object. The program fails to compile with the message p does not name a type which I could not understand why.
Your error is in line:
p = &obj1;
It is better to write like this, it should help:
class caller
{
private:
derived obj1;
base *p = &obj1;
......
};
or initialize pointer in costructor:
class caller
{
private:
derived obj1;
base *p = nullptr;
caller() : p(&obj1) {}
......
};
I started to use googletest and googlemock libraries and I have a problem which I cannot solve. I have a code something like this:
class Painter
{
public:
void DrawSomething();
};
void Painter::DrawSomething()
{
Turtle turtle;
turtle.doSomething();
}
main()
{
Painter p;
p.DrawSomething();
}
I have mocked the Turtle class but how can I test doSomething() method (for example with EXPECT_CALL) when the object of turtle is created locally? Is it possible without modifying Painter class?
Thank you for answers.
I have mocked the Turtle class ...
How exactly did you mock it?
... but how can I test doSomething() method (for example with EXPECT_CALL) when the object of turtle is created locally?
Is it possible without modifying Painter class?
(Emphasis mine)
The straightforward answer is: No.
You cannot magically inject a mock instead of a real instance used in another class without decoupling via an interface.
You should have something like the following code instead:
struct ITurtle {
virtual void PenUp() = 0;
virtual void PenDown() = 0;
virtual void TurnLeft(double degrees) = 0;
virtual void Move(double distance) = 0;
// ...
virtual ~ITurtle() {}
};
struct TurtleMock : ITurtle {
// Mock method declarations
MOCK_METHOD0(PenUp, void ());
MOCK_METHOD0(PenDown, void ());
MOCK_METHOD1(TurnLeft, void (double));
MOCK_METHOD1(Move, void (double));
};
class Turtle : public ITurtle {
public:
void PenUp();
void PenDown();
void TurnLeft(double degrees);
void Move(double distance);
};
Provide the real implementation for the above declarations in a separate translation unit.
class Painter {
public:
Painter(ITurtle& turtle) : turtle_(turtle) {}
void DrawSomething();
private:
ITurtle& turtle_;
};
void Painter::DrawSomething() {
turtle_.PenDown();
turtle_.TurnLeft(30.0);
turtle_.Move(10.0);
turtle_.TurnLeft(30.0);
turtle_.Move(10.0);
// ...
}
You can alternatively pass the ITurtle interface to the DrawSomething() function:
class Painter {
public:
void DrawSomething(ITurtle& turtle);
};
void Painter::DrawSomething(ITurtle& turtle) {
turtle.PenDown();
turtle.TurnLeft(30.0);
turtle.Move(10.0);
turtle.TurnLeft(30.0);
turtle.Move(10.0);
// ...
}
int main() {
NiceMock<TurtleMock> turtle;
Painter p(turtle);
// Painter p; <<< for the alternative solution
EXPECT_CALL(turtle,PenDown())
.Times(1);
EXPECT_CALL(turtle,TurnLeft(_))
.Times(2);
EXPECT_CALL(turtle,Move(_))
.Times(2);
p.DrawSomething();
// p.DrawSomething(turtle); <<< for the alternative solution
}
I have written a wrapper class to mock production code without changing it. Please let me know if there is any flaw in this.
#include "gtest/gtest.h"
#include "src/gtest-all.cc"
#include "src/gmock-all.cc"
#include "src/gmock_main.cc"
#include <iostream>
#include <string>
#include <vector>
using ::testing::An;
using ::testing::AtLeast;
using ::testing::DoAll;
using ::testing::NotNull;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::SetArgReferee;
using namespace std;
class Student
{
int iAge;
public:
Student(int _iAge) : iAge(_iAge)
{
}
virtual void PrintDetails()
{
cout<<"Age:"<<iAge<<endl;
}
virtual bool CheckGrade(int iGrade)
{
return (iGrade - 5) == iAge;
}
};
class StudentFaker
{
static Student* internalObject;
public:
static void FakerSetObject(Student* object) {
internalObject = object;
}
StudentFaker(int _iAge){
}
void PrintDetails() {
internalObject->PrintDetails();
}
bool CheckGrade(int iGrade) {
return internalObject->CheckGrade(iGrade);
}
};
Student* StudentFaker::internalObject = NULL;
class StudentMock : public Student
{
public:
StudentMock(int _iAge) : Student(_iAge) { }
MOCK_METHOD0(PrintDetails,void());
MOCK_METHOD1(CheckGrade,bool(int));
};
#define UNITTEST
bool ProductionCode();
TEST(STUDENT,TEST)
{
StudentMock stMock(8);
EXPECT_CALL(stMock, PrintDetails())
.Times(AtLeast(1))
.WillOnce(Return());
EXPECT_CALL(stMock, CheckGrade(5))
.Times(AtLeast(1))
.WillOnce(Return(true));
StudentFaker::FakerSetObject(&stMock);
EXPECT_TRUE(ProductionCode());
}
//Production code
#ifdef UNITTEST
#define Student StudentFaker
#endif
bool ProductionCode()
{
Student st(8);
st.PrintDetails();
if(st.CheckGrade(5))
return true;
else
return false;
}
//Production code
I am running into a problem about mocking a non-virtual method that need your help.
I referred to the link: Mock non-virtual method giving compilation error
I understood what they did. But I have an advanced question. Assume that I have:
*/
#include <iostream>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using ::testing::Invoke;
using ::testing::NiceMock;
template <class myclass> class Templatemyclass {
public:
myclass T;
void show() ;
};
template <class myclass> void Templatemyclass<myclass>::show()
{
T.show_text();
}
struct Test {
void display() { std::cout << __func__<<":-->Inside the display Test\n"; }
void show_text() {
display(); // HOW to re-route it to my_display() ? (>.<)
}
};
struct MockTest {
MOCK_CONST_METHOD0(display, void());
MOCK_CONST_METHOD0(show_text, void());
};
void my_display(){
{ std::cout <<__func__<<":-->Outside the display Test\n"; }
}
int main() {
//NiceMock<Templatemyclass<Test> > obj1;
//obj1.show();
NiceMock<Templatemyclass<MockTest> > obj2;
EXPECT_CALL(obj2.T, display())
.Times(1)
.WillOnce(Invoke(my_display));
obj2.show();
return 0;
}
I'd like that when show_text is called, it's going to call display. I try to mock display and re-route it to my_display, but that's failed. I got the error.
../test_program.cpp:56: Failure
Actual function call count doesn't match EXPECT_CALL(obj2.T, display())...
Expected: to be called once
Actual: never called - unsatisfied and active
Changing the above source code a bit. It can work, but this missed my expectation. I'd like to mock display that called in show_text.
template <class myclass> class Templatemyclass {
public:
myclass T;
void show() ;
};
template <class myclass> void Templatemyclass<myclass>::show()
{
T.display();
}
struct Test {
void display() { std::cout << __func__<<":-->Inside the display Test\n"; }
// void show_text() {
// display(); // HOW to re-route it to my_display() ? (>.<)
// }
};
struct MockTest {
MOCK_CONST_METHOD0(display, void());
MOCK_CONST_METHOD0(show_text, void());
};
void my_display(){
{ std::cout <<__func__<<":-->Outside the display Test\n"; }
}
int main() {
NiceMock<Templatemyclass<Test> > obj1;
obj1.show();
NiceMock<Templatemyclass<MockTest> > obj2;
EXPECT_CALL(obj2.T, display())
.Times(1)
.WillOnce(Invoke(my_display));
obj2.show();
return 0;
}
And the screen shows:
display:-->Inside the display Test
my_display:-->Outside the display Test
Please help me clear this problem.
You can't use EXPECT_CALL out of a TEST or TEST_F macro. Your main function should invoke the runner and you should place the code you now have in main within a TEST. Check the docs.
I am using VS2005 and gmock ver. 1.6 for unit testing.
I have the following code which I want to mock, but I cannot find a way to do so.
class A
{
virtual bool foo1() = 0;
virtual bool foo2() = 0;
};
class B : public A
{
virutal bool foo1();
virtual bool foo2();
static B* getInstance(int x);
static B* getInstance();
}
Where getInstance(int x) is just creating an instance of B and returns it. Whereas getInstance() just returns the already created instance by getInstance(int x);
I have the mock class,
class MockA : public A
{
MOCK_METHOD0(foo1, bool());
MOCK_METHOD0(foo2, bool());
}
In the sources, I am using
bool retVal = B::getInstance()->foo2()
How can I mock this behavior B::getInstance()?
I think that you have to use linker seam to do what you want.
Let's say that we have libraryToBeMocked with the interface placed in libraryToBeMocked.hpp:
#pragma once
class Base
{
public:
virtual bool evenCheck() = 0;
virtual bool oddCheck() = 0;
};
class Derived : public Base
{
public:
virtual bool evenCheck();
virtual bool oddCheck();
static Base* getInstance(int x);
static Base* getInstance();
private:
Derived(int x);
int x;
};
You should have noticed that I have altered your design. Both getInstance method returns pointer to Base not Derived. If you want to mock the logic clearly you should mock the pure interface Derived already has some logic in it. IMHO both getInstance methods should be moved to other class anyways.
The implementation of the library is in libraryToBeMockedImpl.cpp
#include "libraryToBeMocked.hpp"
#include <memory>
#include <cstdlib>
bool Derived::evenCheck() { return x % 2 == 0; }
bool Derived::oddCheck() { return x % 2 != 0; }
namespace
{
std::auto_ptr<Derived> current(NULL);
}
Base* Derived::getInstance(int x)
{
current.reset(new Derived(x));
return current.get();
}
Base* Derived::getInstance()
{
return current.get();
}
Derived::Derived(int x) : x(x) {}
There is also the logic which you want to test. testedLibrary.hpp:
#pragma once
bool isOdd(int x);
bool isEven(int x);
implementation testedLibraryImpl.cpp:
#include "testedLibrary.hpp"
#include "libraryToBeMocked.hpp"
bool isOdd(int x)
{
return Derived::getInstance(x)->oddCheck();
}
bool isEven(int x)
{
return Derived::getInstance(x)->evenCheck();
}
Dummy main in main.cpp:
#include <iostream>
#include "testedLibrary.hpp"
using namespace std;
int main()
{
int x;
cin >> x;
cout << x << " is odd:" << boolalpha << isOdd(x) << endl;
cout << x << " is even:" << boolalpha << isEven(x) << endl;
return 0;
}
I don't use VS, but I think all it takes is to add main.cpp testedLibraryImpl.cpp and libraryToBeMockedImpl.cpp to the project. I would rather use gcc:
g++ main.cpp libraryToBeMockedImpl.cpp testedLibraryImpl.cpp -o production
Well, let's start with my answer. I would create header file 'libraryMockSeam.hpp':
#pragma once
#include "libraryToBeMocked.hpp"
class Provider
{
public:
virtual Base* getInstance() = 0;
virtual Base* getInstance(int x) = 0;
};
Provider* registerNewMockProvider(Provider*);
and libraryMockSeam.cpp:
#include "libraryMockSeam.hpp"
namespace
{
Provider* currentProvider = 0;
}
Provider* registerNewMockProvider(Provider* newProvider)
{
Provider* t = currentProvider;
currentProvider = newProvider;
return t;
}
Base* Derived::getInstance()
{
return currentProvider->getInstance();
}
Base* Derived::getInstance(int x)
{
return currentProvider->getInstance(x);
}
As you can see this source file provides it's own implementation of getInstance methods. It delegates it to the registered Provider. The headers introduced the Provider interface and a function that allows to register your provider. That's it.
Let's look at the test:
#include "testedLibrary.hpp"
#include "libraryMockSeam.hpp"
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace ::testing;
class MockProvider : public Provider
{
public:
MOCK_METHOD1(getInstance, Base*(int x));
MOCK_METHOD0(getInstance, Base*());
};
class MyMock : public Base
{
public:
MOCK_METHOD0(evenCheck, bool());
MOCK_METHOD0(oddCheck, bool());
};
class MyTestSuite : public Test
{
public:
MyTestSuite()
{
registerNewMockProvider(&provider);
}
StrictMock<MyMock> mock;
StrictMock<MockProvider> provider;
};
TEST_F(MyTestSuite, checksForOddValue)
{
EXPECT_CALL(provider, getInstance(1)).Times(2).WillRepeatedly(Return(&mock));
EXPECT_CALL(mock, evenCheck()).WillOnce(Return(false));
EXPECT_CALL(mock, oddCheck()).WillOnce(Return(true));
EXPECT_TRUE(isOdd(1));
EXPECT_FALSE(isEven(1));
}
TEST_F(MyTestSuite, checksForEvenValue)
{
EXPECT_CALL(provider, getInstance(1)).Times(2).WillRepeatedly(Return(&mock));
EXPECT_CALL(mock, evenCheck()).WillOnce(Return(true));
EXPECT_CALL(mock, oddCheck()).WillOnce(Return(false));
EXPECT_TRUE(isEven(1));
EXPECT_FALSE(isOdd(1));
}
I would compile it like that:
g++ test.cpp testedLibraryImpl.cpp libraryMockSeam.cpp -lgmock -lgmock_main -lpthread -o test
You should notice that I did not provide libraryToBeMocked.cpp in this case, the implementation is already provided by libraryMockSeam.cpp. In case you would like to use whole libraries (that is *.lib files(or *.a)) You would be able to provide both mocked library and the seam but later one should be provided to the linker before the library.
Code:
struct Base { ... };
struct A : public Base { ... };
struct B : public Base { ... };
struct C : public Base { ... };
Is it possible to create an array, that holds that types of struct?
sample/expected result:
Type inheritedTypesOfStruct[3] = {A, B, C};
The purpose of this is that I later want to create an object with a random class retrieved from the array.
You could create an array of functions, each of which returns a base pointer(or smart pointer) that each point to objects of your various derived classes. e.g.
typedef std::unique_ptr<Base> base_ptr;
template<typename Derived>
base_ptr CreateObject()
{
return base_ptr(new Derived);
}
int main()
{
std::function<base_ptr(void)> f[3] = {
CreateObject<A>, CreateObject<B>, CreateObject<C>
};
base_ptr arr[10];
for (int i=0; i<10; ++i)
arr[i] = f[rand()%3]();
}
Here it is in action: http://ideone.com/dg4uq
If your compiler supports RTTI, you can do something like:
const type_info *inheritedTypesOfStruct[3] = {
&typeid(A), &typeid(B), &typeid(C)
};
However, you won't be able to instantiate a class using only its type_info. The factory pattern might be a better answer to your root problem.
Update: Since type_info instances cannot be copied (their copy constructor and assignment operator are private), and arrays of references are illegal, constant pointers have to be used in the example above.
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <map>
#include <vector>
#include <memory>
using namespace std;
// interface
class Base
{
public:
virtual ~Base() { }
virtual int getClassId() = 0;
};
// class A relizes interface Base, has ID == 1 (is used in automatic registration to factory)
class A : public Base
{
public:
const static int ID = 1;
static Base* CreateInstance()
{
return new A();
}
virtual int getClassId()
{
return ID;
}
virtual ~A() { }
};
// class B relizes interface Base, has ID == 2 (is used in automatic registration to factory)
class B : public Base
{
public:
const static int ID = 2;
static Base* CreateInstance()
{
return new B();
}
virtual int getClassId()
{
return ID;
}
virtual ~B() { }
};
// this is the objects factory, with registration only (unregister s not allowed)
class ObjectFactory
{
ObjectFactory() { }
ObjectFactory(ObjectFactory&) { }
public:
virtual ~ObjectFactory() { }
static ObjectFactory& instance()
{
static ObjectFactory objectFactory;
return objectFactory;
}
typedef Base* (*Creator) ();
void registerCreator(int id, Creator creator)
{
registry[id] = creator;
}
Base* CreateById(int id)
{
return registry[id]();
}
private:
map<int, Creator> registry;
};
// this template class is used for automatic registration of object's creators
template <class T>
struct RegisterToFactory
{
RegisterToFactory(ObjectFactory& factory)
{
factory.registerCreator(T::ID, &T::CreateInstance);
}
};
namespace
{
// automaticaly register creators for each class
RegisterToFactory<A> autoregisterACreator(ObjectFactory::instance());
RegisterToFactory<B> autoregisterBCreator(ObjectFactory::instance());
}
// lets this this solution
int main(int argc, char *argv[])
{
vector<int> ids;
ids.push_back(static_cast<int>(A::ID));
ids.push_back(static_cast<int>(B::ID));
srand(time(0));
for (int i = 0; i < 20; ++i)
{
int randomClasssId = ids[rand() % ids.size()];
auto_ptr<Base> testObject(ObjectFactory::instance().CreateById(randomClasssId));
cout << "Object of classId = " << testObject->getClassId() << " has been produced by factory." << endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
I don't get the question. Are you asking for an array that can hold different type of instances at the same time? That is possible using polymorphism, of course. Or are you trying to get an array of types (like reflection)? That would be possible using RTTI or Qt type information (as an example), but I never did that.
You can take a look here: http://www.java2s.com/Code/Cpp/Class/Objectarraypolymorphism.htm
on how to use Polymorphism in C++.