Mock for a concrete class using gmock in C++ - unit-testing

I am stuck with creating a mock for a concrete class.
I know that is not a great idea to do this but I'm not not allowed to change production code.
My code is similar with:
Class A
{
public:
A(B* b)
{
this->b = b;
}
.........................
void function_from_a_to_test(<arg>)
{
if(!b)
b->function_from_b();
else
//something to do
}
private:
B * b;
};
class B
{
........
public:
void function_from_b();
......
};
class MockB : public B , testing::Mock //i don't know why I can that, B is not virtual
{
MOCK_METHOD(function_from_b, void, (void));
};
A_Test :testing::Test{
SetUp()
{
b = new B();
a = new A(b);
}
TearDown()
{
delete b ;
delete a ;
}
void set_b(B * bb)
{
a->b = bb;
}
.........................
}
In order to test I used Test_f
TEST_F(A_Test, Test_function_from_a_to_test)
{
//arrange
//act
B * b_t = new MockB();
set_b(b_t);
EXPECT_CALL(*(static_cast<MockB> b_t), function_from_b))
.Times(10);
function_from_a_to_test(arg);
}
It's seems that the test is passed but i got memory leak at static cast.
And If I store the result of static cast in another variable (in order to delete it), the expect call having that variable is failing.
I know that is not really a good practice, but I can not change the production code.
Has somebody a idea how to solve it?
Or a better way to test this?

You can't mock a non-virtual function using inheritance. You would have to have to define a mock class that implements the functions needed by the code under test, and then have a way to replace the concrete class with the mock class. Read more about it here.
To be honest, I have no idea what the result of that static_cast is, but it's probably not good.
The only way I can think of to do what you want to do without changing production code is to use a different include path in your test project that would allow completely replacing the concrete class B with the mock class B. This may or may not be possible, depending on how your production code is structured.
If you're lucky enough to have class B defined in a separate header file, then it's easy: Make a mock header file with the same name but different folder, and make sure that folder appears in the include path before the production header file's location.
Production B.h file (in original location and unmodified):
class B
{
public:
void function_from_b() {}
};
Mock B.h file (in test code location):
class B
{
public:
MOCK_METHOD(void, function_from_b, ());
};
Somewhere in production code (unmodified):
#include "B.h" // Will load original or mock depending on include path
class A
{
public:
A(B *b)
{
m_b = b;
}
void function_from_a_to_test(int arg)
{
if (m_b)
m_b->function_from_b();
else
; //something to do
}
private:
B *m_b;
}
Test code:
TEST(A_Test, Test_function_from_a_to_test)
{
B b;
A a(&b);
EXPECT_CALL(b, function_from_b)
.Times(1);
a.function_from_a_to_test(0);
}

Related

Variables in Google Test Fixtures

Why TEST_F can access the member variable in a class without using any scopes? e.g.,
class ABC : public ::testing::Test
{
protected:
int a;
int b;
void SetUp()
{
a = 1;
b = 1;
}
virtual void TearDown()
{
}
};
TEST_F(ABC, Test123)
{
ASSERT_TRUE(a == b);
}
why it can directly access a and b, instead of using ABC::a or ABC::b? Does the fixture create a variable for class ABC? if so, should it be ASSERT_TRUE(abc.a == abc.b); instead of ASSERT_TRUE(a == b);?
TEST_F is a macro which defines a new class publicly inheriting from the first argument (in this case, 'ABC'). So it has access to all public and protected members of the test fixture class.
You can inspect the source for this macro in the header file to get a better idea of what it's doing.
TEST_F macro, which if you follow the macro path leads you to...
GTEST_TEST_ macro

Pointer to method without variable, how does this code work?

I came across some code I don't understand. In a class B there is a pointer to a method of a different class A but the pointer has no variable. How can I call this method in class B?
This is part of a larger project of someone else, i would like to preserve the existing code.
class A {
public:
A *root() { return this; }
};
class B {
public:
A *root();
};
I expected something like this
A *myA = root();
inside class B to work but i get linker error "undefined reference to ...". The question is more how this construction is called, what is it useful for and how to use it.
As in the comments standing, there is no implementation of B::root(). Maybe the code you have has beside the .h file a .cpp or .hpp file, where the implementation of B::root() stands - or there exists a library with it.
A valid implementation could be A* B::root() { return new A(); }. You can just grep for B::root.
To call B::root(), a simple B b; A* as = b.root(); is enough. Same as with A::root(), where a simple call could be A a; A* as = a.root();
class A {
public:
A *root() { return this; }
};
class B {
public:
A *root();
};
A* B::root() { return new A(); }
int main() {
A a;
B b;
A* asa = a.root();
A* asb = b.root();
return 0;
}

Overriding method return type with incomplete derived class in C++

I am writing a "filesystem" abstraction in C++, with the following inheritance hierarchy:
[Node]
^
|
+----[Dir]
|
+----[File]
Where Node defines all the behavior identical to both (Name, time last modified, etc.) however, I have a Node method called getParent() that returns a type Dir *. This works fine, because although Dir.h obviously needs to know the implementation specification in Node.h, Node.h doesn't need to know about what's in Dir.h so I can use a forward declaration. Great.
However, I recently decided to add in multiple inheritance so I can support "snapshots" of the filesystem at a certain time. These are read-only versions of the "live" Node File and Dir classes, and since the live versions can be read from as well as written to, I have each live version inherit from its snapshot dual:
[NodeSnapshot] <------ [Node]
^ ^
| |
+---[DirSnapshot]<---+---[Dir]
| |
+---[FileSnapshot]<--+---[File]
Therefore, Dir inherits from both Node and DirSnapshot, and File inherits from both FileSnapshot and Node. Everything looks good to be so far, until we get to the declaration of getParent(). In NodeSnapshot, I return a DirSnapshot *. No problem, I can use a forward declaration again. However, in Node, I want to return Dir *. I, as a programmer, know that Dir is a subtype of DirSnapshot, however the compiler has no way of knowing this because a forward declaration doesn't have any of this useful information embedded in it.
Is it possible to inform the compiler that this forward declaration is a subclass and therefore it shouldn't tell me that the return type of Dir::getParent() does not covary with that of DirSnapshot::getParent()?
It is possible to implement/emulate return type covariance without any language support, though solutions tend to be verbose. On the other hand, mutually recursive definitions are no problem. One needs to use non-virtual public (inline) functions that call virtual private functions. It is a useful technique, some even argue that all interfaces should be implemented like this.
Here's an example:
// forward declare classes
class A;
class B;
class AA;
class BB;
// parents
class A
{
virtual B* getB_impl();
public:
B* getB() { return getB_impl(); }
};
class B
{
virtual A* getA_impl();
public:
A* getA() { return getA_impl(); }
};
// kids
class AA : public A
{
virtual BB* getBB_impl();
B* getB_impl();
public:
BB* getB() { return getBB_impl(); }
};
class BB : public B
{
virtual AA* getAA_impl();
A* getA_impl();
public:
AA* getA() { return getAA_impl(); }
};
// implement parents
B* A::getB_impl() { return new B; }
A* B::getA_impl() { return new A; }
// implement kids
B* AA::getB_impl() { return getBB_impl(); }
BB* AA::getBB_impl() { return new BB; }
A* BB::getA_impl() { return getAA_impl(); }
AA* BB::getAA_impl() { return new AA; }
// check
A a; B b;
A* pa; B* pb;
AA aa; BB bb;
AA* paa; BB* pbb;
pa = b.getA();
pb = a.getB();
pa = bb.getA();
pb = aa.getB();
paa = bb.getA();
pbb = aa.getB();
You should exclude multiple inheritance from your project.
Snapshot is associated with current state of filesystem/dir/file, so it's data.
You need inheritance when you don't want to replicate functional and inherit file and dir from node is acceptable. However since snapshot is data it is likely you need to move node data to some struct, special file/dir data to other structs, all of them will be returned or saved/restored on some functions callings, that will be overloaded due inheritance.
[Node] [Node Data]
^
|
+----[Dir] [Node Data][Dir Special Data]
|
+----[File] [Node Data][File Special Data]
virtual void Node::Snapshot()
{
//some code operating with Node Data (saving on disk for ex)
}
virtual void Dir::Snapshot()
{
Node::Snapshot();
//some code operating with Special Dir Data (saving on disk for ex)
}
virtual void File::Snapshot()
{
Node::Snapshot();
//some code operating with Special File Data (saving on disk for ex)
}

class declaration over different files

I am not able to find a similar question else where on this site, but is it possible to declare a class over two different files.
for example, all public class components in a file and privates and others in a different file.
publics.h
class test {
public:
int geta();
void seta(int);
};
privates.h
class test {
private:
int a;
};
The above way is definitely wrong, but is there any such method.
There is a way to get something quite similar: private inheritance.
// private.hpp
class test_details {
protected:
int a;
};
// public.hpp
#include "private.hpp"
class test : private test_details {
public:
int geta() const { return a; }
void seta(int i) { a = i; }
};
Note that you will still need to (indirectly) include the private header in any module that uses the public class, so you're not really hiding anything this way.
Not like that, but the pimpl idiom (or opaque pointer, or Chesshire cat) can help you achieve similar functionality - you can provide a public interface where all implementation details are hidden in an implementation member.
C++ doesn't support partial classes.
Also, note that what you have there are class definitions, not declarations. C++ mandates that if multiple definitions of a class are available, they must be identical, otherwise it's undefined behavior.
This is a good use case for an abstract base class
//File test.h
class test {
public:
virtual ~test() {}
virtual int geta()=0;
virtual void seta(int)=0;
};
//File test_impl.h
class test_impl : public test {
public:
int geta() { return a; }
void seta(int a ) { a = v; }
private:
int a;
};

How to declare an object from a condition and make it available through the rest of the function?

I have two classes, both with the same function names that do similar things based on user input. I need to do something like this.
if (myapp.advanced == true)
class1 a;
else
class2 a;
But since a is declared from inside the if, it's not available in the next line. How do fix the above condition?
a.something();
Two ways I can think of:
1) Make class1 and class2 derive from some base class classB, then do:
shared_ptr<classB> a;
if(myapp.advanced == true) a.reset(new class1);
else a.reset(new class2);
a->something();
2) Write a template function:
template <typename T> void do_something(T& t)
{
t.something();
}
...
if(myapp.advanced)
{
class1 a;
do_something(a);
}
else
{
class2 a;
do_something(a);
}
Note that the second approach is more suitable if you can't change class1 and class2 to add the base class. I'm also assuming that the bit inside do_something is more complicated than just calling something() on the object in question -- otherwise you could just call it directly!
EDIT: Just to clarify, the second approach doesn't make it available throughout the rest of the function in question -- it adds a new function in which it's available instead.
If these types are related, use a common base class and do this:
const base& a = (myapp.advanced == true) ? static_cast<base&>(class1())
: class2();
a.something();
a.some_other_thing();
a.yet_another_thing();
Temporaries bound to a const reference have their lifetimes extended until the end of the reference's lifetime, so this is safe. However, such hackery wouldn't be necessary (and you can do away with the const, if you need to modify the object) if you separated the concerns object creation and object using into different functions:
void do_something(base& obj)
{
obj.something();
obj.some_other_thing();
obj.yet_another_thing();
}
if (myapp.advanced == true) {
class1 a;
do_something(a);
} else {
class2 a;
do_something(a);
}
If the types are unrelated, you could still do this by turning do_something() into a function templates:
template< class T >
void do_something(T& obj)
{
obj.something();
obj.some_other_thing();
obj.yet_another_thing();
}
if (myapp.advanced == true) {
class1 a;
do_something(a);
} else {
class2 a;
do_something(a);
}
Your coding logic implies that Class1 and Class2 have something in common. Express this in code by having them derive from a common base class.
Then use a base class pointer to hold instances of the derived classes.
There are many ways to approach this, but without further info I would probably advice you to do this:
I suppose the classes have common ancestor called Base
Base* a;
if (myapp.advanced == true)
a = new class1();
else
a = new class2();
Of course you must not forget to issue a delete after you no longer need it or use a smart pointer.
If you find yourself repeating this if-else statement often, this procedure might be better of wrapped in some sort of function or factory class, but it all depends on the circumstances.
I would recommend putting function something() as pure virtual to base class and inherit class1 and class2 from it.
class Base
{
public:
virtual void something() = 0;
virtual ~Base(){}; // since we use Base class pointer the destructor should be virtual
};
class class1 : public Base
{
public:
void something(){ //do stuff
}
};
class class2 : public Base
{
public:
void something(){ //do other stuff
}
};
Here's a sample of usage of this technique:
int main()
{
Base* a = NULL;
if (myapp.advanced == true)
a = new class1();
else
a = new class2();
a->something();
// when the instance is not needed anymore destroy it.
delete a;
}
Like Fred Nurk mentioned in the comments there's other alternatives for using delete operator - auto_ptr, different boost smart pointers. They're widely used by many people (including myself) making it easier to control the life of objects created with new.
Another edit following OP's comment:
Don't forget to put multiple inclusion protection macro in your headers
#ifndef _SOME_UNIQUE_NAME_HERE_
#define _SOME_UNIQUE_NAME_HERE_
// header body goes here
#endif
to avoid multiple including (direct or indirect) of your headers into one cpp.