How to mock method with optional parameter in Google Mock? - c++

How to mock a method with optional parameter in Google Mock?
For example:
class A
{
public:
void set_enable( bool enabled = true );
};
class MockA : public A
{
MOCK_METHOD1( set_enable, void( bool ) ); // this is not working
};

This is an alternative of Marko's answer: If you don't want to change your original code, just implement the helper in the mock class:
class A
{
public:
virtual void set_enable( bool enabled = true );
};
class MockA : public A
{
MOCK_METHOD1( set_enable_impl, void( bool ) );
virtual void set_enable( bool enabled = true )
{
set_enable_impl( enabled );
}
};
You still have to expect calls of set_enable_impl in your tests, for example
MockA mockA;
EXPECT_CALL(mockA, set_enable_impl(true)).Times(Exactly(1));
EXPECT_CALL(mockA, set_enable_impl(false)).Times(Exactly(1));

Change implementation of your method set_enable to use a helper method, like this:
void set_enable( bool enabled = true ) { set_enable_impl(enabled); }
Now, in class MockA, create a mock method for set_enable_impl:
MOCK_METHOD1( set_enable_impl, void( bool ) );
Then, in your production code you simply use set_enable as you would in the first place, while in tests you can set expectations on method set_enable_impl:
MockA mockA;
EXPECT_CALL(mockA, set_enable_impl(_))...;
An alternative would be to overload the method by having versions with one and zero parameters. It is up to you to determine which way works better for your case.

Some modifications to PiQuer's answer. You wouldn't need a wrapper if just add the name, "enabled" to the variable of type bool in your MOCK_METHOD1 like below:
class A
{
public:
void set_enable( bool enabled = true );
};
class MockA : public A
{
MOCK_METHOD1( set_enable, void( bool enabled ) );
};

Set two mocks like this:
class MockA : public A
{
MOCK_METHOD1( set_enable, void( bool ) );
MOCK_METHOD1( set_enable, void( ) );
};

Related

DryIoc call service method upon resolution

How can I make DryIoc resolve Service as usual and immediately afterwards let it call its Adjust( int ) method with some specific parameters?
UPDATE: Based on suggestion provided by dadhi, the code is changed to use RegisterInitializer
public interface IMaster
{
void Run( int val );
}
public class Master : IMaster
{
public Master( IService service )
{
service_ = service;
}
public void Run( int val )
{
service_.Execute( val );
}
private readonly IService service_;
}
public interface IService
{
void Execute( int val );
}
public class Service : IService
{
public void Adjust( int state ) // This method does not belong to the interface
{
Console.WriteLine( "Service state is adjusted with {0}", state );
state_ = state;
}
public void Execute( int val )
{
var result = val + state_;
Console.WriteLine( "Service execution resulted in {0}", result );
}
private int state_;
}
static void Main( string[] args )
{
var container = new Container();
container.Register<Service>( Reuse.Singleton );
container.RegisterInitializer<IService>( ( service, resolver ) =>
{ // Casting type down is a bad idea.
( (Service)service ).Adjust( 5 );
} );
container.Register<IMaster, Master>( Reuse.Singleton,
Parameters.Of.Type<IService>( typeof( Service ) ) );
var master = container.Resolve<IMaster>();
master.Run( 10 );
}
The code above utilizes type cast which is, firstly, dirty enough to be blocked by our code quality standards.
Secondly, another registration may happen to map IService to AlternativeService, which has nothing to do with Adjust method.
So the question is why can I not replace container.RegisterInitializer<IService> with container.RegisterInitializer<Service>?
If I do this initialization code does not get called.
And more generally, is there any way to achieve what I want without explicit type casts? It would be great if we could link initialization to concrete classes rather than to interfaces.
You may need RegisterInitializer method.

How to test method in google test, using std::function?

I would like to test method "methodToTest" in class A:
typedef std::function F_global;
struct A
{
F_global m_F_global;
A(F_global m_F_global) : p_F_global(m_F_global) {}
void methodToTest()
{
m_F_global(5);
}
};
I have got a mock class:
class RunMock
{
public:
MOCK_METHOD1(run, void (int));
};
Below I have got a test case:
class TestClass : public testing::Test
{
protected:
void SetUp();
std::unique_ptr<A> m_aa;
std::unique_ptr<RunMock> m_runMock;
};
void UecSimplePortTestSuite::SetUp()
{
m_aa = make_unique<A>(m_runMock->run);//IT DOESN'T WORK I DON'T KNOW HOW TO FORWARD A METHOD run from RunMock to constructor
}
TEST_F(UecSimplePortTestSuite, testForwardMessage)
{
EXPECT_CALL(*m_runMock, run(_));
m_aa->methodToTest();
}
Generally I don't know how transfer a method "run" from Mock class "RunMock" in "UecSimplePortTestSuite::SetUp()". I would like to do this, because
I would like to "EXPECT_CALL(*m_runMock, run(_));" in UecSimplePortTestSuite.testForwardMessage to test "methodToTest()".
I think that good idea could be to use lmbda, std::boost::bind or something like this.
You can pass a lambda to the constructor of A in the SetUp() :
m_runMock.reset( new RunMock );
m_aa.reset( new A( [&](int value){ m_runMock->run(value); } );
This :
m_runMock->run
is not going to do what you thing, and it is a compilation error. You can read this parashift QA and here how to use pointer to member function.

Design test with templates and inheritance

I have a question regarding a design in C++.
As you see in the code below there is a design problem. I want to be able to have a TestClass which inherits from zero or more classes derived from ModeBase (ModeOne and ModeTwo in this example). If TestClass inherits from ModeOne, it would have the ability to use MethodeOne(), and it would be a requirement for TestClass to implement MethodOne() which is what I want.
class ModeBase
{
//--Methods--------------------------------------------------------------------
public:
virtual ~ModeBase() = default;
};
class ModeOne : private ModeBase
{
//--Methods--------------------------------------------------------------------
public:
virtual ~ModeOne() = default;
virtual void MethodOne() {}
};
class ModeTwo : private ModeBase
{
//--Methods--------------------------------------------------------------------
public:
virtual ~ModeTwo() = default;
virtual void MethodTwo() {}
};
class TestBase
{
//--Methods--------------------------------------------------------------------
public:
TestBase() : currentMode_( nullptr ) {}
virtual ~TestBase() = default;
template <class Mode, class T>
void ChangeMode()
{
if( std::is_base_of<Mode, T>::value )
{
// Class does inherit from Mode so we make sure the current mode
// has changed
currentMode_ = std::make_shared<Mode>();
}
else
{
// Class does not inherit from Mode so we don't do anything
}
}
template <class Mode>
bool CurrentMode()
{
if( std::dynamic_pointer_cast<Mode>(currentMode_) != nullptr )
{
return true;
}
return false;
}
//--Data members---------------------------------------------------------------
private:
std::shared_ptr<ModeBase> currentMode_;
};
class TestOne
: public TestBase
, private ModeOne
, private ModeTwo
{
//--Methods--------------------------------------------------------------------
~TestOne() = default;
void HeartbeatTick()
{
if( CurrentMode<ModeOne>() )
{
MethodOne();
}
else if( CurrentMode<ModeTwo>() )
{
MethodTwo();
}
}
virtual void MethodOne() {}
virtual void MethodTwo() {}
};
class SomeManager
{
~SomeManager() = default;
void ChangeAllMode()
{
for( auto it = vector_.begin(); it != vector_.end(); ++it )
{
// Here is the problem with this implementation. I need to know
// the type of the TestBase derived class (TestOne) to use it as
// a `ChangeMode` method template parameter.
//(*it)->ChangeMode<AIModeFollowLine, SOMETYPE>();
}
};
std::vector<std::shared_ptr<TestBase>> vector_;
};
I already know this is bad design since vector_ will be filled at runtime so I have no way of using ChangeMode like that. It appears that it would be a good solution to use multimethods, wouldn't it ? If so, what would the design look like ?
Multimethods (AKA multiple dispatch) deals with the issue of dispatching a call to a single function based on the runtime type of the parameters involved. This does not appear to be your issue (or have I misunderstood you?), as you have two different method names, implemented on two different types.
Your goal appears to be to select a method implementation based on a runtime type that you have injected into a class. It is not clear whether you are able to dictate the form which that injection takes but if you are then why do you not directly inject the implementation? Then you could use an implicit interface rather than an explicit one. In other words why not inject a functor-like object?
class TestBase
{
public:
typedef std::function<void ()> Ticker;
TestBase(Ticker hbTicker) : ticker{hbTicker} {}
void HeartbeatTick() {
ticker();
}
void setTicker(Ticker hbTicker){
ticker = hbTicker;
}
private:
Ticker ticker;
};
Seems like a lot less complicated to me if that meets your requirements.
If you really do need to implement multiple dispatch you will probably need to implement a visitor pattern on each of the parameters whose runtime type you need to determine. Not sure if that would work for multiple parameters though (I've not tried multiple parameters myself at least). Or you could use RTTI and a case statement or something like that.
I am just being stupid here !
I just have to use a different ChangeMode() method in order to know if TestBase and thus TestOne is of type ModeBase:
template<typename Mode>
bool
IsSame( TestBase* base )
{
return dynamic_cast<Mode*>(base) != nullptr;
};
template <class Mode>
void
ChangeMode()
{
if( isSame<Mode>(this) )
{
// Change the ticker method
}
else
{
}
}

List of pointers to methods of derived classes

I'm trying to create the following in C++:
class A {
SpecialContainer<SpecialType> list_of_callables;
void add_to_container(SpecialType *method); // adds method to the SpecialContainer
};
class B : public A {
void method_1();
};
such that a pointer to method_1 can be inserted into the container using, e.g.,
a.add_to_container(&B::method_1)
and consequently be called in an iteration inside A using for instance
# pseudo code
for item in container
(this->*item)();
(Notice that A does not define method_1).
My question is: is this even possible to do, even if with void*, a boost lib or some
C/C++ hack? If yes, how?
(I'm sorry if the answer is obvious, I came back from Python recently).
So far, I tried using
typedef void (A::*SpecialType)();
and SpecialContainer a std::vector, but with no success since method_1
is obviously from B, i.e. I would have to call
add_to_container(&B::method_1)
which is an invalid compilation.
add_to_container(&B::method_1)
This only works if method_1 was a static member of B. The following code works for me (apart from linking, and std::vector instead of your container class):
class A {
public:
typedef void (*SpecialType)();
std::vector<SpecialType> list_of_callables;
void add_to_container(SpecialType method);
};
class B : public A {
public:
static void method_1();
};
int main()
{
A a;
a.add_to_container(&B::method_1);
return 0;
}
If you want functions bound to specific instances of B check out std::bind if you're using C++11, or boost::bind for older C++.
You can't mix pointers to functions with pointers to member functions, so you cannot implement your callback list in that way.
I have implemented this kind of list many times, in form of a event class. My solution to that problem is to dispatch global handlers and member handlers in two distinct ways, and to use dynamic binding when calling the handlers:
//C#-like event class. It supports global functions and member functions as handlers
template<typename SENDER , typename ARGUMMENTS = void>
class event
{
public:
typedef SENDER& sender_param_type;
typedef ARGUMMENTS& argumments_param_type;
private:
struct handler_data
{
virtual void dispatch( sender_param_type , argumments_param_type ) = 0;
virtual ~handler_data() {}
};
struct global_handler_data : public handler_data
{
typedef std::function<void(sender_param_type , argumments_param_type)> global_handler_type;
global_handler_type handler;
global_handler_data( const global_handler_type& handlerrr ) : handler( handlerrr ) {}
void dispatch( sender_param_type sender , argumments_param_type argumments )
{
handler( sender , argumments );
}
};
template<typename HANDLER_CLASS>
struct member_handler_data : public handler_data
{
typedef void(HANDLER_CLASS::*member_handler_type)( sender_param_type , argumments_param_type);
member_handler_type handler;
HANDLER_CLASS& handler_instance;
member_handler_data( HANDLER_CLASS& handlerrr_instance , const member_handler_type& handlerrr ) : handler_instance( handlerrr_instance ) , handler( handlerrr ) {}
void dispatch( sender_param_type sender , argumments_param_type argumments )
{
(handler_instance.*handler)( sender , argumments );
}
};
std::vector<std::unique_ptr<handler_data>> _handlers;
public:
void add_handler( const typename global_handler_data::global_handler_type& handler )
{
_handlers.push_back( std::unique_ptr<handler_data>( new global_handler_data( handler ) ) );
}
template<typename HANDLER_CLASS>
void add_handler( HANDLER_CLASS& handler_instance , const typename member_handler_data<HANDLER_CLASS>::member_handler_type& handler )
{
_handlers.push_back( std::unique_ptr<handler_data>( new member_handler_data<HANDLER_CLASS>( handler_instance , handler ) ) );
}
void raise_event( sender_param_type sender , argumments_param_type argumments )
{
for(auto& handler : _handlers )
{
handler->dispatch( sender , argumments );
}
}
};
//Non-args evets specialization:
template<typename SENDER>
class event<SENDER,void>
{
public:
typedef SENDER& sender_param_type;
private:
struct handler_data
{
virtual void dispatch( sender_param_type ) = 0;
virtual ~handler_data() {}
};
struct global_handler_data : public handler_data
{
typedef std::function<void(sender_param_type)> global_handler_type;
global_handler_type handler;
global_handler_data( const global_handler_type& handlerrr ) : handler( handlerrr ) {}
void dispatch( sender_param_type sender )
{
handler( sender );
}
};
template<typename HANDLER_CLASS>
struct member_handler_data : public handler_data
{
typedef void(HANDLER_CLASS::*member_handler_type)( sender_param_type );
member_handler_type handler;
HANDLER_CLASS& handler_instance;
member_handler_data( HANDLER_CLASS& handlerrr_instance , const member_handler_type& handlerrr ) : handler_instance( handlerrr_instance ) , handler( handlerrr ) {}
void dispatch( sender_param_type sender )
{
(handler_instance.*handler)( sender );
}
};
std::vector<std::unique_ptr<handler_data>> _handlers;
public:
void add_handler( const typename global_handler_data::global_handler_type& handler )
{
_handlers.push_back( std::unique_ptr<handler_data>( new global_handler_data( handler ) ) );
}
template<typename HANDLER_CLASS>
void add_handler( HANDLER_CLASS& handler_instance , const typename member_handler_data<HANDLER_CLASS>::member_handler_type& handler )
{
_handlers.push_back( std::unique_ptr<handler_data>( new member_handler_data<HANDLER_CLASS>( handler_instance , handler ) ) );
}
void raise_event( sender_param_type sender )
{
for(auto& handler : _handlers )
{
handler->dispatch( sender );
}
}
};
As you can see, the class is designed to dispatch events with two parameters: A reference to the object which raised the event, and the event parameters.
You could use C++11 variadic-templates instead of one aggregate event parameter only, but I have done in this manner because the class had to be compatible with MSVC11.
The class provides exactly the same interface to manage global handlers and member handlers, the add_handler() function is overloaded in that way. The only difference is that member handlers need one object to be called with, so the handler of the event stores a reference to a caller object specified by the user when registers the member handler.
Finally, the class is specialised to allow the user create events without parameters.
Here is an example of its usage:
class rabbit
{
void jump()
{
up.raise
}
}

Create Mock for a constant method in Turtle

I have,
class CFoo : public CFooPar
{
public:
CFoo(){}
~CFoo(){}
virtual bool ret() const
{
return true;
}
};
How can I create mock class for this virtual bool ret() const method?
Thank you!
I use Google Mock for that (https://code.google.com/p/googlemock/wiki/V1_6_ForDummies).
With that tool, the mock reads
#include "gmock/gmock.h"
class MockCFoo : public CFoo {
public:
MOCK_CONST_METHOD0(ret, bool());
};
If you mean using turtle here it is :
#include <turtle/mock.hpp>
MOCK_BASE_CLASS( MockCFoo, CFoo )
{
MOCK_METHOD( ret, 0 )
};
The rest depends on how you use CFoo in your production code, however it would likely be similar to the turtle motivation case I suppose.