#include "gtest/gtest.h"
#include "gmock/gmock.h"
class Turtle{
public:
int foo();
};
int func(){
Turtle local_tutrtle;
auto x = local_tutle.foo();
......
return x;
}
TEST(mock, foo) {
class MockTurtle : public Turtle {
public:
MOCK_METHOD0(foo, int());
};
ASSERT_EQ(10, func());
}
How can I mock the local_turtle in func()? I want to change the return value of local_tutle.foo() without modifying func();
Thanks.
You can't.
You have to supplement mocked object (in your example turtle) from the outside, by passing (mocked or nomral) turtle object as an argument.
This design pattern is called dependency injection, and you should get familiar with it as soon as possible, because it's very important in designing easily testable applications and frequently used.
Related
I am unit testing a derived class and want to EXPECT_CALL that a certain method belonging to its base class is called.
For example:
class Base {
public:
void move(int x, int y);
};
class Derived: public Base{
public:
RESULT update();
private:
int age;
};
HRESULT Derived::update(void) {
int param1 = 5, param2 = 10;
move(param1, param2);
age++;
return SUCCESS;
}
I can't just create a mock for Derived and expect move since there is no dependency and the actual move() will be called.
How can I be able to mock move()? My end goal is that I need to expect move() to be called with CORRECT parameter values (param1 and param2 in this case).
Of course this isn't the actual code but just a representation
I know this is not good design as far as UT is concerned, but this is to test some legacy code I am not allowed to reformat (but need to make UT). So being able to mock and test move() is the best option I have really.
Help will be appreciated. Thanks!
I don't think there is any way without using some preprocessing tricks. And of those tricks making method virtual when testing should be least painfull.
It is enough to do something like:
#if UNDER_TEST
#define TEST_VIRTUAL virtual
#else
#define TEST_VIRTUAL
#endif
class Base {
public:
TEST_VIRTUAL void move(int x, int y);
};
Then you can mock it like this:
class TestObject : public Derived {
public:
MOCK_METHOD2(move, void(int x, int y));
};
TEST(Test, Testing)
{
TestObject obj;
EXPECT_CALL(obj, move(5, 10));
obj.update();
}
In this code there is noting to mock. You do not have here any external dependency.
Test for this code can look like this:
TEST(DerivedTest, WhenUpdateIsCalledPossitionIsChangedAndItGetsOlder)
{
Derived foo;
foo.age = 1;
foo.update();
EXPECT_EQ(10, foo.x);
EXPECT_EQ(12, foo.y);
EXPECT_EQ(2, foo.age);
}
Show me the reason there is sense to mock here anything?
#include <iostream>
using namespace std;
//can't modify it
class Orig{
public:
void Method(){
cout << "I am original method";
}
};
class Mock{
public:
void Method(){
cout << "I am mock method";
}
};
//can't modify it
class UseMethod{
Orig object;
public:
void UseOrigMethod(){
object.Method();
}
};
class UseMethodMock : public UseMethod{
//some code
};
int main()
{
UseMethodMock o;
o.UseOrigMethod();
}
I want to call Method() of Mock class using above code when I call o.UseOrigMethod(); from main. I have tried declaring object of Mock class in UseMethodMock but still it uses Orig's object.
Is there any way we can fool compiler and call Mock's Method when it calls object.Method() in UseMethod class?
I can change code in Mock and UseMethodMock classes but not in others.
There is no shame in modifying code to make it more testable, so maybe you can reconsider. In this case:
Prepare Orig for inheritance by making its methods virtual.
Inject an Orig instance into UseMethod via its constructor (beware slicing – pass by pointer or reference).
Have Mock inherit from Orig and override the virtual methods.
If the performance of virtual calls is a concern, do it all at compile time:
Make UseMethod a template, that takes the type of Orig as a template parameter.
In production code, use UseMethod<Orig>.
In test code, use UseMethod<Mock>.
If you really, absolutely, positively can definitely, certainly not modify Orig and UseMethod, you can abuse the preprocessor:
#include "Orig.h"
#define Orig Mock
#include "UseMethod.h"
#undef Orig
Of course, this comes with a whole boatload of caveats (most notably, it assumes that UseMethod.cpp does not refer explicitly to the Orig type), and in general I would strongly advise against it.
Because you call orig's method. You should override useOrigMethod() in UseMethodMock class.
you just need to change the UseMethod class Orig object to Moke object i will give expected output it means called the method of Moke class.
code:
#include <iostream>
using namespace std;
//can't modify it
class Orig{
public:
void Method(){
cout << "I am original method";
}
};
class Mock{
public:
void Method(){
cout << "I am mock method";
}
};
//can't modify it
class UseMethod{
//need to change here Orig to Moke
Mock object;
public:
void UseOrigMethod(){
object.Method();
}
};
class UseMethodMock : public UseMethod{
//some code
};
int main()
{
UseMethodMock o;
o.UseOrigMethod();
}
output
I am mock method
--------------------------------
Process exited after 0.006435 seconds with return value 0
Press any key to continue . . .
I have some C++ code as follows:
class MyClass
{
public:
MyClass(OtherClass *obj)
{
obj_ = obj;
}
void myMethod()
{
// Do something
int value = obj_->otherMethod();
// Do something else
}
private:
OtherClass *obj_;
}
I want to create a unit test to test the functionality of myMethod(). Unfortunately, OtherClass is an external library and its methods are not declared virtual (so I can't inherit the methods and stub them out in a mock). I have some experience with Mockito where I might have used a spy for this purpose. But I can't seem to find an equivalent in C++.
I'm using the googletest framework for now and the context for this question (if it helps) is in ROS, where I'm actually trying to stub out tf::TransformListener.
Question 1: Is there an alternative to spies that I might not know of and can leverage in this situation?
Question 2: If there isn't, is there a quick-and-easy way for me to restructure my code so that I can leverage a mock?
Solved by doing the following:
class IOtherMethodAdapter
{
public:
virtual int otherMethod() = 0;
}
class OtherClassOtherMethodAdapter : public IOtherMethodAdapter
{
public:
int otherMethod() { return obj_->otherMethod(); }
private:
OtherClass *obj_;
}
Now I use a pointer to IOtherMethodAdapter in MyClass instead of OtherClass and for testing I simply initialize the implementation of the interface to a stubbed/mock object. If there is another way, feel free to post that solution too.
I have see some sample code about gmock,
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <stdio.h>
#include <string>
class MockFoo {
public:
MockFoo() {}
MOCK_METHOD3(Bar, char(const std::string& s, int i, double x));
MOCK_METHOD2(Bar2, bool(int x, int y));
MOCK_METHOD2(Bar3, void(int x, int y));
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
};
class GMockOutputTest : public testing::Test {
protected:
MockFoo foo_;
};
TEST_F(GMockOutputTest, ExpectedCall) {
testing::GMOCK_FLAG(verbose) = "info";
EXPECT_CALL(foo_, Bar2(0, _));
foo_.Bar2(0, 0); // Expected call
testing::GMOCK_FLAG(verbose) = "warning";
}
The mock class MockFoo is mocking three functions as is in the class body, but the class MockFoo does not inherit any class.
If I understand it correctly, the mock class can mock virtual and non-virtual functions.
1) Mocking virtual functions: mock class should inherit a base class being mocked, and all the functions in that class should be virtual, but in this example, there is no base class.
2) Mocking non-virtual functions: mock class does not need inherit any class, but it needs to add tamplate to the code in order to use hi-perf dependency injection.
Does the code above belong to any of the case? And what is it trying to mock? And how to understand it?
The key thing to remember here is that a mock class can override either virtual or non-virtual methods in a superclass, but it doesn't have to. Sometimes it's useful to define a totally standalone mock which doesn't conform to any particular interface or override any other functionality. Consider the case where you are testing a templatized class:
template <typename T>
class Foo {
public:
Foo(T* member) : _member(member) {}
void f() { _member->bar(); }
private:
T* _member;
};
You want to verify that class Foo invokes bar() on the template parameter class, but the template class doesn't need to conform to any formal interface; it just needs to expose a bar() method. In this case you might use a standalone mock:
class MockSomething {
public:
MOCK_METHOD0(bar, void());
};
Just like your example, this mock class has no relationship to another class or interface. It's a standalone mock, and it can be used just as you would any other:
TEST(StackOverflow, StandaloneMock) {
MockSomething mock;
EXPECT_CALL(mock, bar());
Foo<MockSomething> foo(&mock);
foo.f();
}
That code is to test the method Bar2() of template class NaggyMock. To be more precise, it is testing that when you call method Bar2() with parameters 0 and 0, that Bar2() method from the mock is going to be called.
You can look at that as a static dependency injection, since you inject dependency through a template parameter. I would say it is the case 2.
Assuming your template class NaggyMock looks like this :
template< typename Foo >
class NaggyMock
{
public:
bool Bar2(int x, int y)
{
if ( ( 0 == x ) && ( 0 == y ) )
{
return foo.Bar2( 0, 11 );
}
return false;
}
private:
Foo foo;
};
then in the unit test you are testing the case when both parameters are 0. If your real class is using some resource (reading from a network, or from a database, or a file, ...), then to avoid it, and make your unit test very fast, you are going to mock that object. And that is what you are doing. Instead of the class handing the real resource, you are injecting a mock object.
For more information, read :
What is Mocking?
Why prefer template method over dependency injection?
I have 2 classes.
class SomeClass
{
public:
int SomeFunction()
{
return 5;
}
};
class AnotherClass
{
public:
int AnotherFunction(SomeClass obj)
{
return obj.SomeFunction();
}
};
I have made a mock class for SomeClass.
class MockSomeClass : public SomeClass
{
public:
MOCK_METHOD0(SomeFunction, int());
};
Now I want in unit test that when i call AnotherClass.AnotherFunction i get result of my own choice. AnotherFunction uses function of SomeClass.SomeFunction(). I have mocked SomeClass. And I have set that when function of mocked object calls it returs 10. But when i run unit test it returns 5 (origional function). What should i do. Below is the unit test which i have written.
[TestMethod]
void TestMethod1()
{
MockSomeClass mock;
int expected = 10;
ON_CALL(mock, SomeFunction()).WillByDefault(Return(expected));
AnotherClass realClass;
int actual = realClass.AnotherFunction(mock);
Assert::AreEqual(expected, actual);
};
I am using visual studio 2008 and gmock 1.6.0. What is wrong I am doing. on realClass.AnotherFunction i want mocked output from mock.SomeFunction().
The problem is that SomeClass::SomeFunction(...) isn't virtual, make it virtual and it will work.
Update:
There is one more fundamental error that causes it to fail, that is the method signature of
int AnotherFunction(SomeClass obj)
which creates a new SomeClass object instance which will in it's turn cause the normal SomeFunction to be called, you should instead pass a reference to the mocked class as argument.
int AnotherFunction(SomeClass* obj)
and invoke it using
int actual = realClass.AnotherFunction(&mock);