Google Mock unit testing static methods c++ - c++

I just started working on unit testing (using BOOST framework for testing, but for mocks I have to use Google Mock) and I have this situation :
class A
{
static int Method1(int a, int b){return a+b;}
};
class B
{
static int Method2(int a, int b){ return A::Method1(a,b);}
};
So, I need to create mock class A, and to make my class B not to use real Method1 from A class, but to use mock.
I'm not sure how to do this, and I could not find some similar example.

You could change class B into a template :
template< typename T >
class B
{
public:
static int Method2(int a, int b){ return T::Method1(a,b);}
};
and then create a mock :
struct MockA
{
static MockCalc *mock;
static int Method2(int a, int b){ return mock->Method1(a,b);}
};
class MockCalc {
public:
MOCK_METHOD2(Method1, int(int,int));
};
Before every test, initialize the static mock object MockA::mock.
Another option is to instead call directly A::Method1, create a functor object (maybe std::function type) in class B, and call that in the Method2. Then, it is simpler, because you would not need MockA, because you would create a callback to MockCalc::Method1 to this object. Something like this :
class B
{
public:
static std::function< int(int,int) > f;
static int Method2(int a, int b){ return f(a,b);}
};
class MockCalc {
public:
MOCK_METHOD2(Method1, int(int,int));
};
and to initialize it :
MockCalc mock;
B::f = [&mock](int a,int b){return mock.Method1(a,b);};

jomock is one of the feasible solutions for Windows application case
class A
{
public:
static int Method1(int a, int b) { return a + b; }
};
class B : public A
{
public:
static int Method2(int a, int b){
return A::Method1(a, b);
}
};
TEST(JoMock, Method1Test)
{
EXPECT_CALL(JOMOCK(A::Method1), JOMOCK_FUNC(_, _))
.WillRepeatedly(Return(3));
EXPECT_EQ(B::Method2(1, 3), 3);
}
B::Method2(1, 3) returns 3 in this case.

A variant version based on BЈовић's answer that allows not to use template (and error-prone explicit template specialization if your implementation is not in the header files).
However, this will need to make the class A not static anymore.
First, create an interface class
class AIf
{
int Method1(int a, int b) = 0;
};
Let your class A implements AIf
class A : AIf
{
int Method1(int a, int b){return a+b;}
};
Then in your class B, add a static pointer to the AIf
class B
{
static AIf* impl = nullptr;
static int Method2(int a, int b) {return impl->Method1(a, b)}
};
When GMock, just do
class MockA : AIf {
MOCK_METHOD2(Method1, int(int a, int b));
};
Then in your tests, set the impl before calling any functions
MockA mockA;
EXPECT_CALL(...);
B::impl = &mockA;
B::Method2(a, b);

Related

googlemock how to use mocking in test

I'm a beginner with google mock and I'm not sure how to use it and the concept.
If I'm trying to Test a method from a class that is calling some other methods from different classes.
Do I need to mock all these methods from this different classes that my Test method is calling.
Here is a example:
class A {
public:
A () {}
int setnum(int num) {//do some stuff return 1 or 0//
}
private:
int _num;
};
class B {
public:
B (){}
int init(A *a, int number){
if(a->setnum(number))
return 1;
return 0;
}
void setNum(int num){_num=num;}
private:
A *_a;
int _num;
};
class C {
public:
int doSoemthing(A *a, int number){
if (domore(a,number))
return 1;
return 0;
}
int domore(A *a, int number){
if(_b.init(a,number))
return 1;
return 0;
;}
private:
B _b;
};
Do I need to mock all the methods from class A and B that I need to Test my Test method?
Or can I just mock one Class , and test if this class is working.
In order to test C class with mocks, you need to introduce an interface for the dependency than is to be used in C class (here, added BIface). Then you need to use dependency injection of BIface to C class (via added ctor). Having that you will be able to test interactions of B and C classes. IMO A class doesn't need to be mocked in CTest (but most probably need to be tested in BTest)
class A {
public:
A() {} // not needed
int setnum(int num) { // do some stuff return 1 or 0//
}
private:
int _num;
};
class BIface {
public:
virtual ~BIface() = default;
virtual int init(A *a, int number) = 0;
virtual void setNum(int num) = 0;
};
class B : public BIface {
public:
B() {} // not needed
int init(A *a, int number) override {
if (a->setnum(number))
return 1;
return 0;
}
void setNum(int num) override {
_num = num;
}
private:
A *_a;
int _num;
};
class C {
public:
C(BIface &b) : _b{b} {}
int doSoemthing(A *a, int number) {
if (domore(a, number))
return 1;
return 0;
}
int domore(A *a, int number) {
if (_b.init(a, number))
return 1;
return 0;
;
}
private:
BIface &_b;
};
class BIfaceMock : public BIface {
public:
MOCK_METHOD2(init, int(A *, int));
MOCK_METHOD1(setNum, void(int));
};
TEST(CTest, givenDoingMoreWhenInitOfBReturnOneThenReturnOne) {
// can be done in CTest ctor if more tests are needed to avoid code duplciation
BIfaceMock bMock{};
A a{}; // `a` doesn't need to be mocked in CTest. It shall be mocked in BTest as it is dependency of B class, not C class
C testedObject{bMock}; // dependency injection of BFace to C
const auto SOME_INT_PARAM = 42;
// Eq mather is used to match both &a and SOME_INT_PARAM. This confirms proper parameters were passed to init
EXPECT_CALL(bMock, init(&a, SOME_INT_PARAM)).WillOnce(Return(1));
ASSERT_EQ(1, testedObject.domore(&a, SOME_INT_PARAM));
}
I'm not 100% sure but in your example you don't have to use mocks at all. You can create your objects really easy here.
I would use mocks when I would expect that some method will be called and should return specific value - I'm not testing this method but for example if-statment:
A a;
if(a.method())
{
// some logic
}
To manipulate what if will get I would use mocks like this: EXPECT_CALL(aMock.method()).WillOnce(Return(true));
But you can use it in many more situations (e.g: you can avoid creating really big class and replace it with mock object).

How to Merge two classes A and B to define the functions of a abstract class in C++

In my C++ project, I have an abstract class that defines an interface for a dll. Call it CAbstractClass.
I have a class AClass which has defined functions for all but 1 of the functions of CAbstractClass. How do I create a new non-abstract class C to inherit CAbstractClass?
Here's my attempt. It results in the error 'E0322: object of abstract class type "CClass" is not allowed.
#include "stdafx.h"
class CAbstractClass
{
public:
CAbstractClass(void) {};
~CAbstractClass(void) {};
virtual int Fn1(int a) = 0;
virtual double Fn2(int a, int b) = 0;
virtual int Fn3(double a, double b) = 0;
};
class AClass
{
public:
AClass(void) {};
~AClass(void) {};
int Fn1(int a) { return 2 * a; }
double Fn2(int a, int b) { return (double)a / (double)b; }
};
class BClass
{
public:
BClass(void) {};
~BClass(void) {};
int Fn3(double a, double b) { return (int) (a+b); }
};
// My guess at how to combine all the classes.
class CClass : public CAbstractClass, public AClass, public BClass
{
public:
CClass(void) {};
~CClass(void) {};
};
int main()
{
CClass C; // E0322: object of abstract class type "CClass" is not allowed.
return 0;
}
AClass and BClass also have to inherit from CAbstractClass. Fn1 Fn2 and Fn3 just don't implement virtual methods of abstract class so CClass is also abstract
class AClass : public CAbstractClass {
//...
};
class BClass : public CAbstractClass {
//...
};
class CClass : public virtual AClass, public virtual BClass {
//...
};
I'm not sure if it can be done using a single CAbstractClass, but if you split your abstract interface into two separate abstract interfaces, then it is easy enough:
#include <stdio.h>
class CAbstractClassA
{
public:
virtual int Fn1(int a) = 0;
virtual double Fn2(int a, int b) = 0;
};
class CAbstractClassB
{
public:
virtual int Fn3(double a, double b) = 0;
};
class AClass : public CAbstractClassA
{
public:
int Fn1(int a) { return 2 * a; }
double Fn2(int a, int b) { return (double)a / (double)b; }
};
class BClass : public CAbstractClassB
{
public:
int Fn3(double a, double b) { return (int) (a+b); }
};
// My guess at how to combine all the classes.
class CClass : public AClass, public BClass
{
public:
};
int main()
{
CClass C;
printf("Fn1(5) returns %i\n", C.Fn1(5));
printf("Fn2(10,12) returns %f\n", C.Fn2(10,12));
printf("Fn3(3.14,6.28) returns %i\n", C.Fn3(3.14,6.28));
return 0;
}
Here's what I ended up using. I chose it because it leaves AClass alone. There is more work: every member function that comes from AClass must be defined in BClass. Another benefit is that there's no need for a CClass.
#include "stdafx.h"
class BAbstractClass
{
public:
BAbstractClass(void) {};
~BAbstractClass(void) {};
virtual int Fn1(int a) = 0;
virtual double Fn2(int a, int b) = 0;
virtual int Fn3(double a, double b) = 0;
};
class AClass
{
public:
AClass(void) {};
~AClass(void) {};
int Fn1(int a) { return 2 * a; }
double Fn2(int a, int b) { return (double)a / (double)b; }
};
class BClass : public AClass, public BAbstractClass
{
public:
BClass(void) {};
~BClass(void) {};
int Fn3(double a, double b) { return (int)(a + b); }
// Define a function for each of AClass' member functions.
int Fn1(int a) { return AClass::Fn1(a); }
double Fn2(int a, int b) { return AClass::Fn2(a, b); }
};
int main()
{
BClass B;
return 0;
}

No matching function in multiple inheritance

I'm new to inheritance in C++ and decided to try some experiments to learn about this subject.
The code below shows the hierarchy of classes I'm creating:
classes.h
class base
{
protected:
int _a;
int _b;
int _c;;
base(int b, int c);
};
class sub_one : public virtual base
{
public:
sub_one(int a, int b) : base(a, b)
{
// do some other things here
}
// other members
};
class sub_two : public virtual base
{
protected:
int _d;
public:
sub_two(int a, int b, int c = 0) : base(a, b)
{
// do something
}
// other members
};
class sub_three : public sub_one, public sub_two
{
private:
bool flag;
public:
sub_three(int a, int b, int c = 0) : base(a, b)
{
// do something
}
};
classes.c
base::base(int a, int b)
{
// ...
}
The compiler shows me the messages:
no matching function for call to sub_one::sub_one()
no matching function for call to sub_one::sub_one()
no matching function for call to sub_two::sub_two()
no matching function for call to sub_two::sub_two()
I just can't find out what is wrong.
sub_three(int a, int b, int c = 0) : base(a, b)
{
// do something
}
is equivalent to:
sub_three(int a, int b, int c = 0) : base(a, b), sub_one(), sub_two()
{
// do something
}
Since there are no such constructors in sub_one and sub_two, the compiler reports the errors. You can add default constructors to sub_one and sub_two to remove the errors.
sub_three constructor initializes base, and call the default constructor of sub_one and sub_two which doesn't exist, you may need
class sub_three : public sub_one, public sub_two
{
private:
bool flag;
public:
sub_three(int a, int b, int c = 0)
: base(a, b), sub_one(a,b), sub_two(a,b,c), flag(false)
{
// do something
}
};

Inheriting an Abstract Template Class in C++ while specifying the type

Say I have a template, abstract class:
template <class T>
class MyClass {
public:
virtual bool foo(const T a, const T b) = 0;
}
And another class that wants to inherit, while getting rid of the template:
class MyInheritor : public MyClass<int *> {
public:
bool foo(const int* a, const int* b) { /* stuff */ }
}
The above doesn't let me instantiate MyInheritor, saying it's an abstract class. How can I override the pure virtual method?
Because you are not overriding anything here: the const is applied to the int and not to the pointer to int.
Here is the fixed version you probably want:
class MyInheritorFixed : public MyClass<int *> {
bool foo(int* const a, int* const b) override { return true; }
};
Live

Modify constructor parameter values before calling base class constructor

I have following class hierarchy:
class Base { // This class cannot be modified
public:
Base(int a, int b, int c) {
if ( a == 100 && b == 200 && c < 100 ) // whatever condition
throw "Error!";
}
};
class Derived : public Base { // this class can be modified
public:
Derived(int a, int b, int c) : Base(a, b, c) {}
};
class Derived is used in many places in code, so it cannot be replaced with some kind of factory function.
now the question is if there is some construct that would allow me to fix a,b,c values before calling Base constructor?
I know I can use functions like:
Derived(int a, int b, int c) : Base(FixA(a), FixB(b), FixC(c)) {}
int FixA(int a) { /*fix a value*/ return a; }
int FixB(int b) { /*fix b value*/ return b; }
int FixC(int c) { /*fix c value*/ return c; }
but it wont allow me to set correct values in case when a b c values are dependent like in above Base class c-tor example.
I was thinking of extending this to:
Derived(int a, int b, int c) : Base(FixA(a,b,c), FixB(a,b,c), FixC(a,b,c)) {}
int FixA(int a, int& b, int& c) { /*fix a b c values*/ return a; }
int FixB(int& a, int b, int& c) { /*fix a b c values*/ return b; }
int FixC(int& a, int& b, int c) { /*fix a b c values*/ return c; }
I suppose there should also be some kind of flag indicating that fix was already done. I am not sure if this is actually correct c++.
I know the best solution is to actually catch exception.
Consider interposing a class between Derived and Base:
class Derived: public UnpackToBase {
public:
Derived(int a, int b, int c): UnpackToBase(FixParameters(a, b, c))
class UnpackToBase: public Base {
public:
UnpackToBase(FixParameters params): Base(params.a, params.b, params.c)
struct FixParameters {
int a, b, c;
FixParameters(int a, int b, int c): a(a), b(b), c(c) {
// do stuff
}
In C++11 you can use a delegating constructor of Derived:
class Derived: public Base {
public:
Derived(int a, int b, int c): Derived(FixParameters(a, b, c)) { }
Derived(FixParameters params): Base(params.a, params.b, params.c) { }
You can use the singleton pattern to resolve this. Please see the code below. Here the order of initialization of the construction initialization list doesn't matter. However, I'm doubtful, if this can be called elegant.
class Base
{
// This class cannot be modified
public: Base(int a, int b, int c)
{
if ( a == 100 && b == 200 && c < 100 ) // whatever condition
throw "Error!";
}
};
class Validator
{
public:
static Validator& instance(int a_in, int b_in, int c_in)
{
static Validator v(a_in,b_in,c_in);
return v;
}
int& a(){ return m_a;}
int& b(){ return m_b;}
int& c(){ return m_c;}
private:
Validator(int a_in, int b_in, int c_in) : m_a(a_in), m_b(b_in), m_c(c_in)
{
// perform validation and modify the members
// Example validation
if(m_a > 0 && m_b > 0)
{
m_c = 0;
}
}
int m_a;
int m_b;
int m_c;
};
class Derived : public Base
{
// this class can be modified
public:
Derived(int a, int b, int c) : Base(Validator::instance(a, b, c).a(), Validator::instance(a, b, c).b(), Validator::instance(a, b, c).c())
{}
};
int _tmain(int argc, _TCHAR* argv[])
{
Derived d(1,2,3);
return 0;
}
Looks like you don't have a problem with hacking what you have to make something weird happen, so why not use good 'ol macros..
#define FIX_ME(x) //do something
Derived(int a, int b, int c) : Base(FIX_ME(a), FIX_ME(b), FIX_ME(c)) {}