Why is original method mocked by GoogleMock still getting called? - c++

I have been attempting to use GoogleMock to override a few specific methods in a underlying class, however I seem to be getting the base constructor, rather than the mocked object. Is there something obvious I am missing here?
I have been following the following example:
http://blog.divebomb.org/2011/07/my-first-c-cmake-googletest-and-googlemock/
However, in my test, I am still getting my 'printf' called. Any thoughts?
Here are the classes/header files:
A.h:
#pragma once
class A
{
public:
virtual void methodToOverride();
void someConcreteMethod();
int mMemberVariable;
};
A.cpp:
#include "A.h"
void A::methodToOverride()
{
std::printf("Hello World");
}
void A::someConcreteMethod()
{
}
B.h:
#include "A.h"
class B
{
public:
B(A &injectedClass);
~B();
void MethodToTest();
private:
A mA;
};
B.cpp:
#include "B.h"
B::B(A & injectedClass):mA(injectedClass)
{
mA.someConcreteMethod();
}
B::~B(){}
void B::MethodToTest()
{
mA.methodToOverride();
}
MockA.h:
#include "A.h"
#include "gmock\gmock.h"
class MockA : public A
{
public:
MOCK_METHOD0(methodToOverride, void());
};
BTest.cpp:
#include "gtest/gtest.h"
#include "MockA.h"
#include "B.h"
using ::testing::AtLeast;
using ::testing::_;
TEST(BTest, mockObject)
{
// Arrange
MockA injectedMock;
EXPECT_CALL(injectedMock, methodToOverride())
.Times(AtLeast(1));
B classUnderTest(injectedMock);
// Act
classUnderTest.MethodToTest();
}

One major problem is that B::mA is an instance of the A class. It doesn't know anything about child-classes and objects.
The member B::mA either needs to be a reference or a pointer for polymorphism to work.

Related

How to seperate definition and implementation of a derived class constructor?

I would like to learn how to define a derived class constructor in one file so that I could implement it in another file.
public:
Derived(std::string name) : Base(name);
~Derived();
Destructor works as expected, however with constructor I either add {} at the end (instead of a semicolon) and then get redefinition of 'Derived' error or I get asked to add {} instead of a semicolon. What is a way to separate definition and implementation in this case?
Base.h
#include <string>
class Base
{
protected:
std::string name;
...
public:
Base(std::string name);
virtual ~Derived();
...
};
Base.cpp
#include "Base.h"
Base::Base(std::string name)
: name(name)
{
...
}
Base::~Base()
{
...
}
Derived.h
#include "Base.h"
class Derived : public Base {
...
public:
Derived(std::string name);
~Derived();
...
};
Derived.cpp
#include "Derived.h"
Derived::Derived(std::string name)
: Base(name)
{
...
}
Derived::~Derived()
{
...
}
You do it the same way as for any other member function of the class. For example,
base.h
#pragma once
#include <string>
class Base
{
std::string name;
public:
Base() = default;
Base(std::string pname);//declaration
//other members
};
base.cpp
#include "base.h"
#include <iostream>
//definition
Base::Base(std::string pname): name(pname)
{
std::cout<<"Base constructor ran"<<std::endl;
}
derived.h
#pragma once
#include "base.h"
class Derived : public Base
{
public:
Derived(std::string pname);//declaration
};
derived.cpp
#include "derived.h"
#include <iostream>
//definition
Derived::Derived(std::string pname): Base(pname)
{
std::cout<<"Derived constructor ran"<<std::endl;
}
main.cpp
#include <iostream>
#include "derived.h"
#include "base.h"
int main()
{
Derived d("anoop");
return 0;
}
You can separate declaration and definition like so:
class Derived : public Base {
public:
Derived(std::string name); // declaration
// ... other members here
};
Then, elsewhere:
// definition
Derived::Derived(std::string name) : Base(name) {
// ...
}

Casting from an abstract base class reference to derived class reference

I have following C++ code
AbstractClass_01.h
class AbstractClass_01 {
public:
virtual void method_01() = 0;
};
AbstractClass_02.h
class AbstractClass_02 {
public:
virtual void method_02() = 0;
};
ClassA.h
#include "AbstractClass_02.h"
class ClassA : public AbstractClass_02{
public:
void method_02();
void method_03();
};
ClassA.cpp
#include "ClassA.h"
void ClassA::method_02() {}
void ClassA::method_03() {}
ClassB.h
#include "AbstractClass_01.h"
#include "AbstractClass_02.h"
class ClassB : public AbstractClass_01 {
public:
ClassB(AbstractClass_02& _obj);
void method_01();
private:
AbstractClass_02 &obj;
};
ClassB.cpp
#include "ClassB.h"
#include "ClassA.h"
ClassB::ClassB(AbstractClass_02& _obj) : obj(_obj) {}
void ClassB::method_01() {
static_cast<ClassA&>(obj).method_03();
}
main.cpp
#include "ClassA.h"
#include "ClassB.h"
int main(int argc, char** argv) {
ClassA a;
ClassB b(a);
b.method_01();
return 0;
}
My question is whether the casting which I have done in the ClassB::method_01 is common C++ construct whether it is a sign of wrong design?
EDIT:
The reason why the ClassB constructor accepts references to the AbstractClass_02 instead of the ClassA is that I need to pass references to various objects which all have common interface AbstractClass_02. The problem is that this interface doesn't contain the method_03. One possible solution could be to append that method into the interface AbstractClass_02 but that method isn't cohesive with the method_02.
This is known as downcasting and is typically a sign of bad design. Based on the limited knowledge we have, it seems obvious that you should take ClassA in constructor instead of AbstractClass_01
#include "AbstractClass_01.h"
#include "ClassA.h"
class ClassB : public AbstractClass_01 {
public:
ClassB(ClassA & _obj);
void method_01();
private:
ClassA &obj;
};
But we don't know your real problem and why did you decide to go with casting or accepting interface in the first place.

Calling Function in MainClass using SubClass

I already saw many answers how to create (e.g.) A class with an object B b and a B class with an object A a
like:
B:
class A;
class B{
A& a;
};
A:
class A{
B b;
};
but if I want to call a function from A in B I got: Invalid use of incomplete type 'class A'
What can I do? I think I know why the compiler say that, but I don't know how to fix it.
Here my latest Code:
Main.cpp:
#include "mainclass.h"
int main()
{
MainClass mainClass;
mainClass.print();
return 0;
}
MainClass.h:
#ifndef MAINCLASS_H
#define MAINCLASS_H
#include <iostream>
#include "subclass.h"
class MainClass
{
SubClass sub;
public:
void print() { sub.print(); }
void printTest() { std::cout << "test" << std::endl; }
};
#endif
SubClass.h:
#ifndef SUBCLASS_H
#define SUBCLASS_H
class MainClass;
class SubClass
{
MainClass* main;
public:
void print() { main->printTest(); }
protected:
private:
};
#endif
The main problem with your code is that the definition of MainClass and SubClass are mutually dependent, therefore the use of the header guards will forbid the inclusion of both header files in the same translation unit (i.e. the union of a cpp file and the all the header files included.)
The forward declaration of class MainClass in subclass.h could solve this problem, since the SubClass::main is a pointer (check the PIMPL idiom), but since you have included the implementation of the class methods in the in the header files, the compiler fails when the SubClass::print() method makes a reference to MainClass::printTest() because it knows nothing about the class MainClass except the fact that it is defined somewhere else.
On the other hand, changing the forward declaration with the explicit inclusion of mainclass.h in subclass.h is not a solution, because of the header guards, as said above.
The simple solution is to split the declaration and the implementation of you classes in .h and .cpp files. If you do so, the compiler will work on multiple translation units: one for the mainclass.cpp, one for the subclass.cpp and one for the main.cpp. When processing the subclass.cpp translation unit, the compiler will be able to include the file mainclass.h and will have the complete definition of MainClass to "see" that a MainClass::printTest() method exists.
Here is the mainclass.h:
#ifndef MAINCLASS_H
#define MAINCLASS_H
#include <iostream>
#include "subclass.h"
class MainClass
{
SubClass sub;
public:
void print();
void printTest();
};
#endif
the mainclass.cpp file:
#include <iostream>
#include "mainclass.h"
void MainClass::print()
{
sub.print();
}
void MainClass::printTest()
{
std::cout << "test" << std::endl;
}
The subclass.h file:
#ifndef SUBCLASS_H
#define SUBCLASS_H
class MainClass;
class SubClass
{
MainClass* main;
public:
void print();
};
#endif
the subclass.cpp:
#include "mainclass.h"
//#include "subclass.h" // already included with the previous line
void SubClass::print()
{
main->printTest();
}
and finally the main.cpp:
#include "mainclass.h"
int main()
{
MainClass mainClass;
mainClass.print();
return 0;
}
This will compile and will apparently work, because it will print the string "test" even if the main pointer is not initialized, and points to an undefined memory area.
This happens because the printTest method does nothing but producing a side effect, i.e. printing on screen. Indeed it does not access to any data member of the MainClass through the this pointer, and therefore you have no memory access violation. Indeed, invoking a method on a not instantiated pointer is an undefined behavior, so it would be better to avoid it, as well as cyclic dependencies.
You can't call a function (MainClass::printTest) that does not exist yet.
You can declare the function inside the SubClass, but define it after you have the MainClass definition.
#include <iostream>
class MainClass;
class SubClass
{
MainClass* main;
public:
void print();
protected:
private:
};
class MainClass
{
SubClass sub;
public:
void print() { sub.print(); }
void printTest() { std::cout << "test" << std::endl; }
};
void SubClass::print() { main->printTest(); }
int main()
{
MainClass mainClass;
mainClass.print();
return 0;
}
Avoid creating function bodies in H files and put the function body into Cpp file.
MainClass.h:
#ifndef MAINCLASS_H
#define MAINCLASS_H
#include <iostream>
#include "subclass.h"
class MainClass {
SubClass sub;
public:
void print();
void printTest();
};
#endif
MainClass.cpp:
#include <iostream>
#include "mainclass.h"
void MainClass :: print () { sub.print(); }
void MainClass :: printTest() {std::cout << "test" << std::endl; }
SubClass.h
#ifndef SUBCLASS_H
#define SUBCLASS_H
#include "mainclass.h"
class SubClass
{
MainClass* main;
public:
void print();
protected:
private:
};
#endif
SubClass.cpp
#include "mainclass.h"
#include "subclass.h"
void SubClass::print ()
{
main->printTest();
}
you can actually #include "mainclass.h" in your subclass.h because it is guarded by #ifdef
You have a design problem:-
How come in SubClass.h compiler will know class MainClass has a method printTest so that it can link to it as you did not included the header file for the definition of MainClass
Another problem is you can not even include MainClass.h in SubClass.h because you are reference to SubClass sub; in it.
MainClass* main; pointer main never initialized and hence this statement void print() { main->printTest(); } is also wrong here.

Circular dependencies C++

I'm trying to compile something like the following:
A.h
#include "B.h"
class A {
B * b;
void oneMethod();
void otherMethod();
};
A.cpp
#include "A.h"
void A::oneMethod() { b->otherMethod() }
void A::otherMethod() {}
B.h
#include "A.h"
class B {
A * a;
void oneMethod();
void otherMethod();
};
B.cpp
#include "B.h"
void B::oneMethod() { a->otherMethod() }
void B::otherMethod() {}
Until now I haven't had problems using forward declarations, but I can use that now, because i can't use atributtes or methods of only-forward-declarated classes.
How can I solve this?
In C++, unlike Java and C#, you can define a member function (providing its body) outside the class.
class A;
class B;
class A {
B * b;
void oneMethod();
void otherMethod() {}
};
class B {
A * a;
void oneMethod();
void otherMethod() {}
};
inline void A::oneMethod() { b->otherMethod(); }
inline void B::oneMethod() { a->otherMethod(); }
As long as I'm understanding your question right, all you need to do is this:
A.h
class B;// Forward declaration, the header only needs to know that B exists
class A {
B * b;
void oneMethod();
void otherMethod();
};
A.cpp
#include "A.h"
#include "B.h"//Include in the .cpp since it is only compiled once, thus avoiding circular dependency
void A::oneMethod() { b->otherMethod() }
void A::otherMethod() {}
B.h
class A;// Forward declaration, the header only needs to know that A exists
class B {
A * a;
void oneMethod();
void otherMethod();
};
B.cpp
#include "B.h"
#include "A.h"//Include in the .cpp since it is only compiled once, thus avoiding circular dependency
void B::oneMethod() { a->otherMethod() }
void B::otherMethod() {}
You must defer using the members of a class until after that class is defined. In your case, that means moving some member function bodies to the bottom of the file:
class B;
class A {
B * b;
void oneMethod();
void otherMethod() {}
};
class B {
A * a;
void oneMethod() { a->otherMethod() }
void otherMethod() {}
};
inline void A::oneMethod() { b->otherMethod() }
Here is a typical solution in multiple files:
A.h
class B;
class A {
B * b;
void oneMethod();
void otherMethod();
};
B.h
class A;
class B {
A * a;
void oneMethod();
void otherMethod();
};
A.cpp
#include "A.h"
#include "B.h"
void A::oneMethod() { b->otherMethod() }
void A::otherMethod() {}
B.cpp
#include "A.h"
#include "B.h"
void B::oneMethod() { a->otherMethod() }
void B::otherMethod() {}
main.cpp
#include "A.h"
int main () { A a; a.oneMethod(); }
Push the implementation of your functions into cpp files and then the cpp can include both headers.

Solving cross referencing

I have a problem creating some form of hierarchy with different object types. I have a class which has a member of another class, like this:
class A
{
public:
A(){}
~A(){}
void addB(B* dep){
child = dep;
dep->addOwner(this);
}
void updateChild(){
child->printOwner();
}
void print(){
printf("Printing...");
}
private:
B* child;
};
And this is class B:
class B
{
public:
void addOwner(A* owner){
ownerObject = owner;
}
//ISNT WORKING
void printOwner(){
ownerObject->print();
}
private:
A* ownerObject;
};
Calling a function of "B" out of class "A" works just fine but trying it vice versa gives a compiler error because A is not defined in B. It actually is by using an include and a forward declaration, but I guess its a cross reference problem which the compiler can not solve.
Is there any chance to solve this problem or should I rethink my design?
You say that you already solved your circular dependency problem by using a forward declaration of A instead of including the header where A is defined, so you already know how to avoid circular includes. However, you should be aware of what is possible and what is not with incomplete types (i.e. types that have been forward declared).
In your case, you try to call the member function print on an object that has an incomplete type; the compiler knows nothing about this type excepts that it will be defined at some point, so it does not allow you to do this. The solution is to remove the implementation of the printOwner member function from the B header and put it into an implementation file:
//B.hpp
class A; // forward declaration
class B
{
public:
void addOwner(A* owner);
void printOwner() const; // I think this member function could be const
private:
A* ownerObject;
};
//B.cpp
#include "B.hpp"
#include "A.hpp" // here we "import" the definition of A
void B::addOwner(A * owner)
{
ownerObject = owner;
}
void B::printOwner() const
{
ownerObject->print(); //A is complete now, so we can use its member functions
}
You could possibly do the same thing in the A header.
You can use forward declaration, and define the member functions outside of the class, i.e.
// A.h
class B;
class A { public:
void addB(B* dep); // don't define addB here.
...
};
// B.h
class A;
class B { public:
void addOwner(A* owner); // don't define addOwner here.
...
};
// A.cpp
#include "A.h"
#include "B.h"
void A::addB(B* dep) {
...
}
// B.cpp
// similar.
You probably should rethink your design, since a crcular parent-child relationship is usually a code smell.
But, you can make the compiler happy :
#include <cstdlib>
#include <cstdio>
class A
{
public:
A(){}
~A(){}
void addB(class B* dep);
void updateChild();
void print(){
printf("Printing...");
}
private:
class B* child;
};
class B
{
public:
void addOwner(A* owner){
ownerObject = owner;
}
//ISNT WORKING
void printOwner(){
ownerObject->print();
}
private:
A* ownerObject;
};
void A::addB(class B* dep){
child = dep;
dep->addOwner(this);
}
void A::updateChild(){
child->printOwner();
}
int main()
{
return 0;
}
You should move B::printOwner implementation to .cpp file.