Better MOCKing? - c++

Question:
Let's say I have a class System which has some Component inside. In order to properly test the System I need to keep a pointer to Component in the System class, and design the Component to have an interface, IComponent, with virtual methods. Then in the test, I can create a mock of IComponent and give it to the System.
But in some situtations I don't want such approach.
There is other technique of using templates and specifying the Component as template parameter, like this:
template <class Component>
class System
{
// ...
Component _component;
};
Then, in my test I can create the System giving it a Mock of Component, like this:
System<MockComponent> theSystem;
The MockComponent does not necesarrily be inherited from IComponent, in my approach I dont want IComponent, I just want MockComponent to have some needed methods, the same as in Component.
But the problem with this approach is that I want to instruct the MockComponent what to do, give it some expectations and tell what to return. From the test I do not have access to the MockComponent because it lives in the System. If the System had a getter of Component then it would be OK, but sometimes I don't want to have a getter of Component in the System. Then, in the test, I need to create another class, MockSystem, and equip it with the getter of the component (and also make sure that the _component in the original System is in "protected" section).
template <Class Component>
MockSystem : public System
{
public:
Component GetComponent() { return _component; }
};
Then, in the test I can:
MockSystem<MockComponent> theSystem;
MockComponent mockComponent = theSystem.GetComponent();
EXPECT_CALL(mockComponnent, ...);
This approach works fine.
But... I wonder if there is a way to simplify this a bit.
What if I had a mechanism of generating, in compile time, the class of MockSystem, from the class of System? I mean I would like to obtain the class of System with getters for all template parameters.
I know that template metaprogramming can do miracles, but I am not an expert in TPM. I've read some examples and seen Boost::Hana in action, and wonder now if this is doable.
Has anyone of guys here heard of or seen a framework for something like this?
Or is there another approach?

You can define wrapper over your mock class - to allow access to mock:
struct ComponentMock
{
MOCK_METHOD0(foo, int());
};
struct ComponentMockWrapper
{
static ComponentMock* mock;
int foo()
{
return mock->foo();
}
};
ComponentMock* ComponentMockWrapper::mock;
Then, in your TestSuite:
class SystemTestSuite : public testing::Test
{
protected:
ComponentMock componentMock;
void SetUp() override
{
ComponentMockWrapper::mock = &componentMock;
}
System<ComponentMockWrapper> objectUnderTest;
};
And test like this:
TEST_F(SystemTestSuite1, shallFooComponent)
{
EXPECT_CALL(componentMock, foo());
objectUnderTest.foo();
}
But be aware of such problems like - what to do if 2 or more Component needed, or how to keep track of lifetime of testable Component...
Maybe better approach is to sacrifice a little encapsulation in favor of testability - i.e. get protected access to component:
template <class Component>
class System
{
protected:
Component& getComponent(); // for UT only
};
And allow public access in UT by promoting this function:
template <class Component>
class SystemTestable : public System<Component>
{
public:
using System<Component>::getComponent;
};
class SystemTestSuite : public testing::Test
{
protected:
SystemTestable<ComponentMock> objectUnderTest;
};

Related

gmock: force mocking out of a class method without defining and referencing a mock class?

the normal pattern of gmock testing is
class MyMockClass : public MyRealClass {
/// swap out behavior of an existng method
MOCK_method(some_method .....);
}
TEST() {
MyMockClass mock;
EXPECT_CALLED(mock.some_method);
/// ******* here I have to explicitly pass in the mock obj into the system
MyConsumerClass myconsumer(mock);
myconsumer.do_something_to_trigger_mock__some_method();
}
in the above "****" line I have to explicitly pass in a mock obj into the system, i.e. compose my consumer obj with a mock obj. But now I face an existing consumer class impl, its constructor does not allow passing in the dependency objects; in fact I can probably argue that it's impossible to list all the dependency objects in the ctor of a consumer class; more importantly, my real case is that the consumer class to be tested sits several levels above the mock obj:
class MyConsumerClass {
private:
MyHelperClass helper
public:
void trigger() {
helper.trigger_again();
}
}
class MyHelperClass {
BottomClass bottom;
public:
void trigger_again() {
bottom.do_something();
}
}
class BottomClass {
public :
void do_something();
}
in this case, in our unit test, we can only instantiate the top level MyConsumerClass, and I was hoping to verify that when I call myconsumer.trigger(), I could verify that the BottomClass.do_something() is called, possibly also verifying that it's called with a specific argument. But the above class hierarchy is written so that I can not pass in a mock BottomClass obj from the top level.
in jmock or jmockit, I remember it's possible to globally wipe out the behavior of BottomClass.do_something(), without referring to a specific mock obj, i.e. "static mocking", as they are called in jmockit. is it possible to do something like that in gmock (c++)? thanks
Converting the comment to an answer:
I can think of two things:
Why don't you test your classes separately? For example, write a separate test for MyHelperClass.
If dependency injection doesn't work for you, GMock allows you to do static mocking by templatizing your classes: Convert your classes to templates, then instantiate the template with real classes for production and with mock classes for testing. See here for an example.
In your case, your code could be rewritten to something like this:
//-----------------------------------------------------------------------------
// Real classes used in production
//-----------------------------------------------------------------------------
class BottomClass {
public:
void do_something();
};
//-----------------------------------------------------------------------------
// Templatized classes used in test or production
//-----------------------------------------------------------------------------
template <class BType>
class MyHelperClass {
public:
BType bottom;
public:
void trigger_again() { bottom.do_something(); }
};
template <class BType, template <typename> class HType>
class MyConsumerClass {
public:
HType<BType> helper;
public:
void trigger() { helper.trigger_again(); }
};
//-----------------------------------------------------------------------------
// Mocked classes used in test
//-----------------------------------------------------------------------------
class MockedBottomClass {
public:
MOCK_METHOD(void, do_something, (), ());
};
TEST(BottomClassTest, Test1) {
MyConsumerClass<MockedBottomClass, MyHelperClass> mock;
EXPECT_CALL(mock.helper.bottom, do_something());
mock.trigger();
}
I had to convert some of your private members to public members for the test to work.
Live example here: https://godbolt.org/z/qc3chdxKz

C++ Reusable module class design

I have many, many modules that can benefit from using the exact same design pattern and share common classes. On the individual component level, everything makes sense, classes can easily be extended. But when I try to tie them together into a common module object, it seems like a pattern that polymorphism wasn't meant for, and I am missing the right pattern or design.
Starting out with all the base classes, which all other classes will extend from. The Module is the glue and the problem. Module will contain methods that prevent code duplication, such as AddComponent.
// A physical interface (Ethernet, Bluetooth, etc)
class Interface {};
// A basic component
class Component {};
// An std::map wrapper for managing Components
class ComponentManager {};
// A place to store data
class Database {};
// A module to tie all things together
class Module {
public:
Interface interface;
ComponentManager manager;
Database db;
void AddComponent(Component& c) {
manager.AddComponent(c);
db.InsertComponent(c);
}
};
Everything is fine until we want to extend all or most of the classes and the Module as well.
class EthInterface : public Interface {}; // cool
class UdpClientComponent : public Component {}; // cool
class UdpClientDatabase : public Database {}; // cool
//class UdpClientComponentManager : public ComponentManager {}; // 90% of the time won't need it
class UdpClientModule : public Module {
public:
EthInterface interface; // how to get an EthInterface instead of Interface?
UdpClientDatabase db; // how to get a UdpClientDatabase instead of Database?
};
I am trying to understand what pattern or design or what to use here. I think templates might not be the right solution because I've simplified this example, and don't think templates with 5 or 6 Ts are good design. I don't really get how to design this using ptrs because then I am feeding the extended Module ptrs from the outside, and I want this to be self contained, so that people can just write UdpClientModule module and they get batteries included, so to speak.
This might be a kick in the dark, but maybe it will send you searching in a different direction... You could use templates, redefining Module to look something like this:
template <class IFC, class COMP, class CM, class DB> class Module {
public:
IFC interface;
CM manager;
DB db;
void AddComponent(COMP& c) {
manager.AddComponent(c);
db.InsertComponent(c);
}
};
But if you go that way you should make sure that IFC, COMP, CM and DB are derived from Interface, Component, ComponentManager and Database and for that you need concepts. I don't know about you, but that is a bit over my head, so I would go a different way:
class Module {
public:
Module(Interface &ifc, Database &_db) :
interface(ifc),
manager(), db(_db) {
}
void AddComponent(Component& c) {
manager.AddComponent(c);
db.InsertComponent(c);
}
private:
Interface &interface;
ComponentManager manager;
Database &db;
};
class UdpClientModule : public Module {
public:
UdpClientModule() :
Module(ethInterface, udpClientDb),
ethInterface(),
udpClientDb() {
}
private:
EthInterface ethInterface;
UdpClientDatabase udpClientdb;
};
It's still clumsy, but it at least gets you some of the way to where (I assume) you want to get.
Interfaces depends from abstraction, you want to depend from concrete types and there where your design flaw. Keep the interface to do the "interface" and leave the concrete classes dealing with the concrete types.
class Module {
public:
virtual ~Module() = default;
void AddComponent(Component& c) {
manager().AddComponent(c);
db().InsertComponent(c);
}
virtual Interface& interface() = 0;
virtual ComponentManager& manager() = 0;
virtual Database& db() = 0;
};
class UdpClientModule : public Module {
public:
Interface& interface() override { return ethInterface; }
ComponentManager& manager() override { return udcClienddb; }
Database& db() override { return manager; }
void specialUdpMethod() const { /*...*/}
private:
EthInterface ethInterface;
UdpClientDatabase udpClientdb;
ComponentManager manager;
};
In this case you're stating every module must provide an interface, e component manager and a db. If you have more relaxed constraint you could move the dependencies to a dependency injection solution and use pointer instead.

How to make expectations on a mock object created inside the tested object?

I want to unit test a class that looks like this:
template <typename T>
class MyClass {
...
void someMethod() {
T object;
object.doSomething();
}
...
};
I want to unit test this class, so I create a mock class for T:
struct MockT {
...
MOCK_METHOD(doSomething, 0, void());
...
};
Then I want to use it in a test case:
BOOST_AUTO_TEST_CASE(testSomeMethod) {
MyClass<MockT> myClassUnderTest;
MOCK_EXPECT(???)....;
myClassUnderTest.someMethod();
}
How do I make an expectation for this object? My first idea was to store all created MockT instances in a static container from the constructor, then delete them from the container from the destructor. This would work if the object were created in a different method than where it is used, like this:
myClassUnderTest.createTheObject();
MOCK_EXPECT(MockT::findMyObject().doSomething);
myClassUnderTest.useTheObject();
But for this I would need to modify the interface of my class, and I really don't want to do that. Is there anything else I can do?
You can use Typemock Isolator++ if you don't want to modify your interface or introduce extra indirection.
template <typename T>
class MyClass
{
public:
void someMethod()
{
T object;
object.doSomething();
}
};
class RealType //RealType is the actual production type, no injection needed
{
public:
void doSomething(){}
};
Since T is created inside someMethod (inside under test method), we need to fake the T's ctor.
FAKE_ALL does just that. The behavior set on fakeRealType will apply to all RealType instances created in runtime. The default FAKE_ALL behavior is a recursive fake, meaning that all the fakes's methods are faked and will return fake objects. You can also manually set any behavior you want on any method.
TEST_CLASS(MyTests)
{
public:
TEST_METHOD(Faking_Dependency_And_Asserting_It_Was_Called)
{
RealType* fakeRealType= FAKE_ALL<RealType>();
MyClass<RealType> myClassUnderTest;
myClassUnderTest.someMethod();
ASSERT_WAS_CALLED(fakeRealType->doSomething());
}
};
Typemock fakes are not strict, so you need to write an appropriate assert to make sure that your method was indeed called. You can do it using ASSERT_WAS_CALLED which is also provided by Typemock.
P.S I used MSTest.
You could redirect the doSomething member function to a static one e.g.
struct MockT
{
void doSomething() {
soSomethingS();
}
MOCK_STATIC_FUNCTION( doSomethingS, 0, void(), doSomething )
};
Then your test would be
BOOST_AUTO_TEST_CASE(testSomeMethod) {
MyClass<MockT> myClassUnderTest;
MOCK_EXPECT(MockT::doSomething).once();
myClassUnderTest.someMethod();
}
If needed you can test the construction and destruction of the object instance, but it likely doesn't bring much more to your test.
I found that the best is to use a shared pointer for the member. It is unfortunate that I have to use an extra indirection just because of the unit test, but at least it works well.
template <typename T, typename TFactory>
class MyClass {
...
void someMethod() {
std::shared_ptr<T> object = factory();
object->doSomething();
}
...
TFactory factory;
};
Then in the test it looks something like this:
BOOST_AUTO_TEST_CASE(testSomeMethod) {
std::shared_ptr<T> mockT;
MockTFactory factory(mockT);
MyClass<MockT, MockTFactory> myClassUnderTest(factory);
MOCK_EXPECT(mockT->doSomething).once();
myClassUnderTest.someMethod();
}

Whats best way to go from a String to Type (C++)

I want to be able to specifiy a type in as a string and create that type in C++. I know C++ doesn't support that directly but whats the best way to approach this?
I currently have an xml that contains information but I want to expand that to include components.
<entity>
<component>ComponentA</component>
<component>ComponentB</component>
</entity>
I have a generic factory that takes in these xml's and builds up the entities. I want to be able to avoid if("componentA") { new ComponentA; } in favour of something more generic. Primarily as the components will be defined by the client and the factory is not.
I thought that components could register themselves with the factory and store a map, but that would require holding a copy of all the components which I'd like to avoid.
I crossplatform solution would be preferable.
AFAIK, at least with general C++, there's no implicit way to create a class using just a string. However, there is another mechanism I have used in the past.
Firstly, you define the notion of a component:
class Component /* or IComponent if you're feeling adventurous - we may not have interfaces in C++, but dammit we like 'em! */
{
protected:
Component() { };
public:
virtual ~Component() = 0 { };
}; // eo class Component
And a notion of a some kind of creator:
class ComponentCreator
{
protected:
Component() { };
public:
virtual ~ComponentCreator() = 0 { };
virtual Component* create() const = 0; // Might want to use smart-pointers here - this is for illustrative purposes only.
}; // eo class ComponentCreator
Ok, we have the basics now we need a factory that can have these creators registered against it:
class Factory
{
private:
std::map<std::string, ComponentCreator*> _creators;
public:
Factory() : _creators(new std::map<std::string, ComponentCreator*>();
{
};
~Factory()
{
// cleanup of _creators ommited.
};
// call to register a creator
void register(const std::string& name, ComponentCreator* creator)
{
// normally you'd put checks to see if it exists etc.
_creators[name] = creator;
}; // eo register
// call to create an instance
Component* create(const std::string& name)
{
std::map<std::string, ComponentCreator*>::const_iterator cit(_creators.find(name));
if(cit != _creators.end())
return cit->create();
else
return NULL; // or nullptr
}; // eo create
}; // eo class Factory
Declare your classes thusly (I will do just one):
class ComponentA : public Component { /* implementation */ };
And don't forget the creator:
class ComponentCreatorForA : public ComponentCreator
{
public:
virtual Component* create() const { return new ComponentA(); };
}; // eo class ComponentCreatorForA
During initialisation of your program, you register component creators:
factory.register("componentA", new ComponentCreatorForA());
factory.register("componentB", new ComponentCreatorForB());
And later on, we can then create components by name:
Component* component = factory.create("componentA");
Notes:
This approach assumes components are known at compile-time. If not one could introduce a plugin-architecture so that additional DLLs can register their components via the factory on start-up so you could make it extensible without having to re-deploy everything.
In the real world we'd use smart pointers of some such, and typedef a lot of that stuff away to make it easier on typing!
You have to store meta-information about your component classes. A possible solution might use templates:
// the component interface
class BaseComponent {...}
// structure containing meta-information
template<typename ComponentType>
struct tComponentMeta {
typedef ComponentType type;
std::string componentTypeName;
tComponentMeta() : componentTypeName("no valid component type") {}
}
// providing run time type information
// (optional, but i like it if the component know about their type
template<typename ComponentType>
class TComponent : public BaseComponent
{
tComponentMeta<ComponentType> metaInfo;
TComponent(const std::string& uniqueTypeName) {...};
}
class ConcreteComponent : public TComponent<ConcreteComponent>
{
...
}
Now the client has to define the specialized tComponentMeta for the ConcreteComponent type. This can be achieved by adding the following code after the class declaration of ConcreteComponent:
template <>
struct tComponentMeta {
typedef ConcreteComponent type
tComponentMeta() : componentTypeName("ConcreteComponent") {}
}
So if you clients define the template specialization for the components you can provide them with a generic factory that has a template method of the following type, that also has to be invoked by the client designing the component:
...
template<typename ComponentType>
registerComponentType() {
tComponentMeta<ComponentType> metaInfo;
nameToMetaMap.put(metaInfo.name, metaInfo)
}
with these building blocks you can generate components in a generic way by forcing the client to provide tComponentMeta specializations of their components and register the component-type at your generic factory.
This code has not been tested by myself so you can assume that there are some syntax errors but I hope the idea is clear.
Due to the nature of templates that approach shall also work in a plug-in architecture that uses DLLs.

Is partial class template specialization the answer to this design problem?

Say you have a class who's job it is to connect to a remote server. I want to abstract this class to provide two versions, one that connects through UDP and the other through TCP. I want to build the leanest runtime code possible and instead of using polymorphism I am considering templates. Here is what I'm envisioning but I'm not sure it's the best way of doing this:
class udp {};
class tcp {};
template<class T,typename X>
class service
{
private:
// Make this private so this non specialized version can't be used
service();
};
template<typename X>
class service<udp, X>
{
private:
udp _udp;
X _x;
};
template<typename X>
class service<tcp, X>
{
private:
tcp _tcp;
X _x;
};
So the end benefit is that the genericness of T is still available, but the very different code required to setup a UDP or TCP connection has been specialized. I suppose you could put it both into one class, or provide another class that adheres to some pure virtual interface for setting up the network connection, like IConnectionManager.
But this does leave the problem of the code for the generic T now having to be written in and maintained in both specialized versions, where they are ultimately the same. How best to address this? I have a feeling I am going about this all wrong.
This can be best done using a policy for the transport protocol:
template<typename Transport>
class service : Transport {
public:
typedef Transport transport_type;
// common code
void do_something() {
this->send(....);
}
};
class tcp {
public:
void send(....) {
}
};
class udp {
public:
void send(....) {
}
};
typedef service<tcp> service_tcp;
typedef service<udp> service_udp;
Note that this is also polymorphic. It's called compile time polymorphism. Putting the policy into a base class will benefit from the Empty-Base-Class-Optimization. That is, your base class does not need to take any space. Putting the policy as a member has the other drawback that you always have to delegate stuff to that member, which can become annoying with time. The book Modern C++ Design describes this pattern in-depth.
Ideally, the transport protocol doesn't need to know anything about the protocol above it. But if for some reason you have to get some information about it, you can use the crtp pattern wiki:
template<template<typename Service> class Transport>
class service : Transport<service> {
// since we derive privately, make the transport layer a friend of us,
// so that it can cast its this pointer down to us.
friend class Transport<service>;
public:
typedef Transport<service> transport_type;
// common code
void do_something() {
this->send(....);
}
};
template<typename Service>
class tcp {
public:
void send(....) {
}
};
template<typename Service>
class udp {
public:
void send(....) {
}
};
typedef service<tcp> service_tcp;
typedef service<udp> service_udp;
You don't have to put your templates into headers. If you explicitly instantiate them, you will gain faster compilation times, as much fewer code has to be included. Put this into service.cpp:
template class service<tcp>;
template class service<udp>;
Now, code that uses service does not need to know about the template code of service, since that code is already generated into the object file of service.cpp.
I would use the curious recuring template pattern, aka Five Point Palm Exploding Alexandrescu Technique:
template <typename Underlying>
class Transmit
{
public:
void send(...)
{
_U.send(...)
};
private:
Underlying _U;
};
class Tcp
{
public:
void send(...) {};
};
class Udp
{
public:
void send(...) {};
};
There would probably be many more template parameters and sub classes but you get the idea, you can also use static methods.
By the way template code is generally more efficient but also much bigger.
Templates are not necessary (though a possible solution). This is just dependency injection via templates rather than via a constructor. Personally I would do it via a constructor. But doing it via template gives you the dubious benifit of a cheaper method call (it does not need to be virtual). But also does allow for easier compiler optimization.
Both the udp and tcp objects must still support the same interface.
If you do it via inheritance they must both implement a common interface (virtual base class), it it is done via templates this is not necessary but the compiler will check that they support the same method calls that the Service object requires.
As asked in the original question, I see no explicit need(or benefit) for partial template specialization (in the situation as described).
Template Method
class udp {/*Interface Plop*/static void plop(Message&);};
class tcp {/*Interface Plop*/static void plop(Message&);};
template<typename T>
class Service
{
public:
void doPlop(Message& m) { T::plop(m);}
// Do not actually need to store an object if you make the methods static.
// Alternatively:
public:
void doPlop(Message& m) { protocol.plop(m);}
private:
T protocol;
};
Polymorphic Version
class Plop{virtual void plop(Message&) = 0;} // Destruct or omitted for brevity
class upd:public Plop {/*Interface Plop*/void plop(Message&);};
class tcp:public Plop {/*Interface Plop*/void plop(Message&);};
class Service
{
public:
Service(Plop& p):protocol(p) {};
void doPlop(Message& m) { protocol.plop(m);}
private:
Plop& protocol;
};
I think that the main point in choosing amongst polimorphism or template specialization, in this particular case at least, is if you want to choose which behavior to use at run time or at compile time.
If you want to have a udp or a tcp connection based, for example, on a connection string provided the user, then polimorphism best fits your needs; create a concrete class and then pass it to generic code that handles a pointer to a base interface.
Otherwise, you might consider using templates - I'm not sure if you need template specialization.
Hope this helps :)