How to mock a member variable of dependency? - c++

I've got a class and member:
class A
{
B obj;
public:
int f(int i){return obj.g(i);}
}
Here B obj is a dependency that requires run-time creation from a file. In my unit test for class A, I wish to mock B obj, with a function g typed int(int).
How can I write my test code, to mock B obj, and then test A::f.
Thanks a lot.

You need to use dependency injection to achieve this. To this end, have class B inherit from an interface, and have class A hold a pointer to that interface:
class IB
{
public:
virtual void g(int i) = 0;
};
class B : public IB
{
public:
void g(int i) {
// this is your real implementation
}
};
Also, to enable dependency injection in class A, add appropriate constructor or setter method:
class A
{
private:
IB *obj;
public:
A() : obj(nullptr) {}
// You don't need both the constructor and setter, one is enough
A(IB *pB) : obj(pB) {}
// void setB(IB *pB) { obj = pB; }
int f(int i) { return obj->g(i); }
};
Now, in your production code you create an object of class B and pass it to class A object (assuming that we are using the constructor for injection):
B b;
A a(&b);
During testing phase, you create a mock class BMock and pass an object of that class to class A object:
class BMock : public IB
{
public:
MOCK_METHOD1(g, int(int));
};
TEST(ATests, TestCase1)
{
BMock bmock;
A a(&bmock);
// Now you can set expectations on mock object, for example that g will
// return 100 when it receives 50 as argument
EXPECT_CALL(bmock, g(50)).WillOnce(Return(100));
// Now act by calling A::f, which will in turn call g from mock object,
// and assert on function return value
ASSERT_EQ(a.f(50), 100);
}

To do this, take a pointer of B instead of object in class A and make your unit Test class (FixtureA ) as friend class in A.
class A
{
B *obj;
public:
int f(int i){return obj.g(i);}
friend class FixtureA;
};
In FixtureA.h you can have following code
class FixtureA
{
public:
void Testf();
}
In FixtureA.cpp
TEST_F(FixtureA , Testf)
{
Testf();
}
void FixtureA::Testf()
{
A objA;
objA.obj = new BMock();
objA.f(2);
}
In BMock class , you can mock the g() function.

You can't do it with the code you have. You have hardcoded your dependency inside the A class. To make mocking possible you have to use some of the dependency injection patterns. One of the possible ways is to have a pointer(better smart) to your B class and in the A constructor you will get a pointer to B with which you will initialize your inner B*. That way you will be able to put a mocked object in your tests.

Related

How to simulate an EXPECT_CALL with gtest

In the code below I tried to explain my problem on a basic model.
class A
{
public:
A() {}
virtual void foo() {}
virtual ~A(){}
//...
};
class B : public A{
public:
B(){}
//...
//does not contain the override function foo()
};
class MustBeTested{
public:
MustBeTested(){
//...
}
void function()
{
m_elem->foo();
//...
}
private:
B* m_elem;
};
class Mock : public B {
public:
Mock() {}
MOCK0(foo, void());
};
//test function from above class
void TestFunction
{
Mock* dummy = new Mock;
EXPECT_CALL(*dummy, foo()).Times(1);
//i know it is wrong becase the called method is A::foo();
}
I have a basic class A that contains a virtual method.
Derivative class B no longer contains the overwritten method foo ().
The MustBeTested class contains the function to be tested, the class member is type B *.
Initially without looking I started to make a Mock class derived from B to simulate EXPECT_CALL ().
I realized that it is not possible because the method in A :: foo () will always be called.
My question is, if there is a workaround without making changes to the class A or B code?
foo in B is not overriden, but it is there - with the default implementation from A. foo is virtual and can be overriden in classes that derive from B, like your Mock (that wouldn't be possible if foo was marked final in B). Your code will work if you will use dependency injection in MustBeTested, see Dependency injection with unique_ptr to mock.

Google testing of composite classes in C++

I have below piece of code written:
//Source code sample
//Class A is the class under test
class A{
public:
A(){
B *b = new B;
}
void func1()
{
b->func2();
}
};
class B
{
void func2()
{
//here a function from third class is called.
}
};
//Test case
class MockB : public B
{
MOCK_METHOD0(func2(), void());
}
TEST_F(A, TC1_func1)
{
MockB mock;
A *a = new A;
a->func1();
EXPECT_CALL(mock, func2()).Times(1);
}
Here the body of func1 contains just a call to func2. I want to write a test case for func1.
My question is, how can we test whether the func2() is called or not from func1?
Note:
class A creates the instance of class B
I do not want to pass the pointer of class B as an argument to the constructor of class A
I do not want to make any changes to the source code.
Thanks in advance.

c++ make a class knowing about another object

if I have something like this:
class A: public Mother{
public:
A(B b){ b_pointer = &b; };
void update() override { int value = b_pointer->getSomething(); };
private:
B* b_pointer;
};
class B{
public:
void update(//parameters);
int getSomething();
};
then in another part of the program, let's say in the class C, both a B and A object are created.
B b_object;
b_object(//attributes of C needed as parameters);
A a_object(b_object);
so, will b_pointer refers to b_object?
if inside a method of A I use b_pointer->getSomething(); will it always refer to b_object?
because i need to update a_object making it knowing about b_object, but I can't write the void A::update() method like update(B& b) {b.doThings()} since A::update overrides a Mother method and in the class C i have a vector of Mothers* to be updated.

Using a Factory to create a class, which is used in another class

I have the following situation:
Factory class implementation:
class FactoryClassA {
public:
FactoryClassA(){};
~FactoryClassA(){};
ClassA create(double a, double b) {
return ClassA;
};
};
ClassA implementation:
class ClassA {
friend class FactoryClassA
~FactoryClassA() {}
private:
ClassA(double a = 0, double b = 0)
{
a(a),
b(b)
};
double a;
double b;
};
OtherClass implementation:
class OtherClass {
public:
OtherClass() {
ClassFactory myClassAFactory;
aClassA = myClassAFactory.create();
}
~OtherClass() {};
private:
aClassA;
};
Unfortunately, this does not work. Because in the (empty) member initializer list of OtherClass, the empty constructor of ClassA is called, which does not exist.
The reason why I made the constructor of ClassA private, is that I want the user to only create objects of ClassA through the FactoryClassA.
First of all, create() should have a return type:
ClassA create(double a, double b) {
return {a, b};
}
I am not going through all the other syntactic bugs. Please fix them, because others might find your question when they search for answers. Please make it easy for them to understand your question.
This has to be in your code after ClassA has been defined, because the compiler has to know the size of a ClassA object as well as the constructor to use.
Second, just initialize your members before the constructor body:
OtherClass() :
aClassA{ClassFactory{}.create(0.0, 0.0)}
{}
You might prefer to have create() as a static member function of ClassFactory. Then the OtherClass constructor looks like this:
OtherClass() :
aClassA{ClassFactory::create(0.0, 0.0)}
{}
That is more intuitive.
This code is full of small errors, that make it unuseable. First syntax for member initialization for a class is :
class A {
A(x, y): m_a(x) { ... }
...
}
and class declaration are statements so they need the final ;
Next, the dtor for a class must be public if you want to be able to use temporary objects.
The default values should not be in ClassA ctor but on create factory method.
Finally, you should use a static factory in OtherClass, no need to create a new factory for each object.
Code becomes:
class FactoryClassA;
class ClassA {
public:
friend class FactoryClassA;
~ClassA(){}
private:
ClassA(double a, double b):a(a),b(b){}
double a;
double b;
};
class FactoryClassA {
public:
FactoryClassA(){}
~FactoryClassA(){}
ClassA create(double a = 0, double b = 0) {
return ClassA(a, b);
}
};
class OtherClass {
public:
OtherClass(): aClassA(myClassAFactory.create()){}
~OtherClass(){}
private:
static FactoryClassA myClassAFactory;
ClassA aClassA;
};
FactoryClassA OtherClass::myClassAFactory;
Not far from original one, but this ones compiles...

Call a class function from within a child class

Suppose an object of class B is a member of class A.
class B{
//Definitions
}
class A{
public:
A();
B b_child;
int some_function();
}
One of the functions defined inside B needs to call a (public) function from its owner (parent?) A. Is there an immediate way to do this?
The only way I've managed to do this so far was to implement it outside the classes' definitions:
A a_obj;
a_obj.b_child.setowner(&aobj);
which tells b_child who is its owner. I don't like this. I'd rather use some builtin method for b_child to access its parent (if possible). If that's not possible, I'd rather pass the owner's address directly in the constructor for B, but I don't know how to reference A's address inside its definition.
There is no builtin method to get the 'owner' of a variable, whatever that means. Your approach of setting the owner is correct. Furthermore, doing so in the construction of B is also a correct decision. Sample code:
class B
{
public:
explicit B( A* owner ) : _owner( owner ) {}
...
private:
A* _owner;
};
class A
{
public:
A() : _child( this ) {}
...
private:
B _child;
};
Note some compilers may give you a warning for using this in that context, but its ok for the current example. Just make sure you don't call any A member functions from within B constructor, since the pointer you get still points to an unconstructed object at that stage.
I'd rather use some builtin method for b_child to access its parent (if possible).
No, it's not.
but I don't know how to reference A's address inside its definition.
You can use this pointer.
A() : b_child(this) { }
You should use this pointer to refer to the object within itself
class B{
//Definitions
}
class A{
private:
B b_child;
public:
A()
{
b_child.set_owner(this);
}
}
You should define B like the following:
template <class T, int N>
class B
{
public:
int example_func() { return static_cast<T&>(*this).some_function(); }
};
And then make B<A> a subclass of A (so it can call A directly).
class A : protected B<A,0>, protected B<A,1>
{
A();
int some_function() { return 42; }
};
This is called the curiously recurring template pattern.
If you don't want B to be a template class, and you're only going to use B with A, then the following is fine:
template <int N>
class B
{
public:
int example_func() { return static_cast<A&>(*this).some_function(); }
};
class A : protected B<0>, protected B<1>
{
A();
int some_function() { return 42; }
};
Alternatively, if you want to use B with not just A, but don't want to make B a template class (say, if you want a collection of pointers to B), you can do the following:
template <int N>
class B
{
public:
int example_func() { return some_function(); }
virtual int some_function() = 0;
};
class A : protected B<0>, protected B<1>
{
A();
int some_function() { return 42; }
};
This will resolve the some_function() call at run-time, and require a virtual pointer to be stored in your class.