google mock - how to mock object owned by class under test - c++

In this example
class A
{
public:
A();
~A();
virtual void func1();
virtual void func2();
protected:
virtual void func3();
private:
// How do I mock this
NetworkClass b;
}
How do I mock NetworkClass b object?
I don't think it's possible to do this solely using google-mock macros.
You'd have to redefine the identifier NetworkClass to actually mean NetworkClassMock and then (for purpose of the test) rename the original NetworkClass to something else like NetworkClass_Orig.
But that still doesn't help you access the private member NetworkClass b for the purpose of the test.

You cannot mock b as it is. You will need to use Dependency Injection.
First you will need to specify a Base Class (or interface) and derive your NetworkClass and NetworkClassMock from INetworkClass. Then you can pass aa raw pointer (better a smart pointer like std::unique_ptr) or a reference to class A. This input can be either your real implementation NetworkClass or your mock NetworkClassMock.
See this example:
#include <iostream>
class INetworkClass
{
public:
virtual void doSomething() = 0;
};
class NetworkClass : public INetworkClass
{
public:
void doSomething() override {std::cout << "Real class" << std::endl;} ;
};
class NetworkClassMock : public INetworkClass
{
public:
void doSomething() override {std::cout << "Mock class" << std::endl;};
};
class A
{
public:
A(INetworkClass& b) : b(b) {};
~A() {};
void func1() {b.doSomething();};
private:
// How do I mock this
INetworkClass& b;
};
int main(){
NetworkClass real_class;
NetworkClassMock mock_class;
A a1(real_class);
A a2(mock_class);
a1.func1();
a2.func1();
return 0;
}
If you just want to access your private member, e.g. to read it's value after doing some tests you should redesign your code. Accessing private members from outside your class is not a good design. If you still want to do this you could check this answer (written for C# instead of C++ but still usable).
P.S. To use the override keyword you will need to compile with C++11 support.

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.

Virtual function behavior in derived classes

Can I have a virtual function in the base class and some of my derived classes do have that function and some don't have.
class A{
virtual void Dosomething();
};
class B : public A{
void Dosomething();
};
class C : public A{
//Does not have Dosomething() function.
};
From one of my c++ textbook:
Once a function is declared virtual, it remains virtual all the way down the inheritance, even if the function is not explicitly declared virtual when the derived class overrides it.
When the derived class chooses not to override it, it simply inherits its base class's virtual function.
Therefore to your question the answer is No. Class c will use Class A's virtual function.
Derived classes do not have to implement all the virtual functions, unless it is a pure virtual function. Even in this case, it will cause an error only when you try to instantiate the derived class( without implementing the pure virtual function ).
#include <iostream>
class A{
public :
virtual void foo() = 0;
};
class B: public A{
public :
void foo(){ std::cout << "foo" << std::endl;}
};
class C: public A{
void bar();
};
int main() {
//C temp; The compiler will complain only if this is initialized without
// implementing foo in the derived class C
return 0;
}
I think the closest you might get, is to change the access modifier in the derived class, as depicted below.
But, I would consider it bad practice, as it violates Liskov's substitution principle.
If you have a situation like this, you might need to reconsider your class design.
#include <iostream>
class A {
public:
virtual void doSomething() { std::cout << "A" << std::endl; }
};
class B : public A {
public:
void doSomething() override { std::cout << "B" << std::endl; };
};
class C : public A {
private:
void doSomething() override { std::cout << "C" << std::endl; };
};
int main(int argc, char **args) {
A a;
a.doSomething();
B b;
b.doSomething();
C c;
//c.doSomething(); // Not part of the public interface. Violates Liskov's substitution principle.
A* c2 = &c;
c2->doSomething(); // Still possible, even though it is private! But, C::doSomething() is called!
return 0;
}

is it possible to have a virtual class declaration in a class?

I'm setting a up an interface for various components of a framework in a personal project, and i've suddenly thought of something that i figured might be useful with an interface. My question is whether this is possible or not:
class a
{
public:
virtual class test = 0;
};
class b : public a
{
public:
class test
{
public:
int imember;
};
};
class c : public a
{
public:
class test
{
public:
char cmember; // just a different version of the class. within this class
};
};
sort of declaring a virtual class or pure virtual class, that is required to be defined within the derived object, so that you might be able to do something like this:
int main()
{
a * meh = new b();
a * teh = new c();
/* these would be two different objects, but have the same name, and still be able
to be referred to by an interface pointer in the same way.*/
meh::test object1;
teh::test object2;
delete meh;
delete teh;
return 0;
}
msvc++ throws me a bunch of syntax errors, so is there a way to do this, and i'm just not writing it right?
No, it isn't valid. In any case, C++ has no concept of virtual classes as such. You can probably achieve what you want by holding a pointer to a certain class with only pure virtual methods (although that isn't a requirement):
class ITest { /* full of pure virtual methods... maybe. */};
class a
{
public:
virtual ITest* someFunctionName()=0 ;
private:
ITest* test_;
};
Then you can decide to inherit from a, giving each implementation concrete implementations of ITest, or some other approach, such as deciding which implementation to use based on some constructor parameter, for example.
The keyword "virtual" merely means "table to dispatch function call.
What you proposed is not part of the language.
But you can approach it in another way, by chaining the object creation to proper virtual calls:
#include <iostream>
using namespace std;
class a
{
public:
class test
{
public:
virtual ~test() {} ///< required to have polimorphic behavior
virtual void hello() const =0;
};
virtual test* create_test()=0;
};
class b: public a
{
public:
class test_b: public a::test
{
virtual void hello() const
{ cout << "this is test_b at " << this << endl; }
};
virtual test* create_test()
{ return new test_b; }
};
class c: public a
{
public:
class test_c: public a::test
{
virtual void hello() const
{ cout << "this is test_c at " << this << endl; }
};
virtual test* create_test()
{ return new test_c; }
};
int main()
{
a* pa1 = new b;
a* pa2 = new c;
a::test* p1 = pa1->create_test();
a::test* p2 = pa2->create_test();
p1->hello();
p2->hello();
delete p2; delete p1;
delete pa2; delete pa1;
}

Figuring out the class of an inheriting object

I have a linked list of Foo objects. Foo is a base class, which has several classes inherit from it. Say, classes A, B, and C.
I am cycling through this linked list and calling a method some_method, which has 3 definitions; one for each child class:
some_method(A a);
some_method(B b);
some_method(C c);
The linked list is generic, so it is of type Foo, as it has an assortment of A, B and C objects.
When I'm cycling through the linked list at current_element, calling some_method(current_element);, how can I make it call the right method? The compiler complained until I wrote a some_method that took the generic Foo, and it only calls into that method.
Depending on your requirements, you may want to consider using polymorphism. To do this, add a pure virtual method to your base node class, and move the corresponding methods to the derived classes.
class Foo
{
public:
virtual void some_method() = 0;
};
class A : Foo
{
public
virtual void some_method()
{
// move the body of some_method(A a) here
}
};
For this to work, your linked list will need Foo*, instead of Foo.
class Node
{
public:
Foo* foo;
Node* next;
};
// ...
Node* someNode = GetNode();
// Calls correct method - A::some_method, B::some_method, or C::some_method
someNode->foo->some_method();
If you can't put some_method in Foo/A/B/C, then you might want to look into the Visitor design pattern:
http://en.wikipedia.org/wiki/Visitor_pattern
This is the "double dispatch" problem. You can use the visitor pattern. Usually the Visitor is a base class so you can re-use this design for multiple problems.
#include <iostream>
class FooVisitor;
class Foo
{
public:
virtual void some_method() = 0;
virtual void visit(FooVisitor* v) = 0;
};
class A;
class B;
class FooVisitor
{
public:
virtual void visit(A* a){ std::cout << "A" << std::endl;}
virtual void visit(B* b){std::cout << "B" << std::endl;}
};
class A : public Foo
{
public:
virtual void some_method()
{
// move the body of some_method(A a) here
}
virtual void visit(FooVisitor* v) { v->visit(this);}
};
class B : public Foo
{
public:
virtual void some_method()
{
// move the body of some_method(A a) here
}
virtual void visit(FooVisitor* v) { v->visit(this);}
};
int main()
{
FooVisitor fv;
Foo* f1 = new A;
f1->visit(&fv);
Foo* f2 = new B;
f2->visit(&fv);
getchar();
}
Two ways:
1) the better way:
Reverse your design such that someMethod is a virtual method of the base class Foo and redefine it in the derived classes. As:
class Foo {
public:
virtual void someMethod() = 0;
};
class A {
public:
void someMethod() { /* implementation specific to A here */ };
};
class B {
public:
void someMethod() { /* implementation specific to B here */ };
};
class C {
public:
void someMethod() { /* implementation specific to C here */ };
};
Then calling the someMethod on a pointer to Foo will automatically call the method from the appropriate class. If that cannot be done because someMethod cannot be implemented as part of Foo or its derivatives (e.g. it needs access to private members of the class it is currently in in your design), then you might try to split this functionality apart into subproblems that can be put into virtual methods of these classes A B C.
2) the "I don't have a choice" way:
Use RTTI (Run-Time Type Identification), it is included in C++. It requires that your base class Foo has at least one virtual method. You need to #include <typeinfo>, then use typeid() on the pointer, it will return a type_info object, and you can compare its name() result with the class names A B and C. This isn't a very nice approach because it has more overhead and it breaks OOP design principles. But if that's the only option, it's fine.
RTTI is your friend here. The example given in the link will guide you further
You can call the method for the child class as a member method. For exampleA a = new A(); a.some_method() should call the correct the method. Within some_method() you can reference to object using keyword this.

C++ is it possible to make a class extend one class and be a realization of an interface at the same time?

Coluld you provide a simple code example? (sorry C++ nube) and how to call a function from the class you are extending?
A bit useful example: :-)
class CImplementation
{
public:
void doFoo();
};
void CImplementation::doFoo()
{
//implementation
}
class IInterface
{
public:
virtual void foo()=0;
};
class DerivedFromImplementationAndInterface : public CImplementation, public IInterface
{
virtual void foo();
};
void DerivedFromImplementationAndInterface::foo()
{
doFoo();
}
//possible usage:
void method(IInterface& aInterface)
{
aInterface.foo();
}
void test()
{
IInterface* d = new DerivedFromImplementationAndInterface;
method(*d);
}
In C++, you can extend multiple classes, it's called multiple inheritance. Most probably this is what you're looking for. Please read a good book about multiple inheritance and C++ (a quick introduction: http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr134.htm), because there are many pitfalls and details to pay attention to.
Example for multiple inheritance:
class A { ... };
class B { ... };
class C: public A, public B {}; // C inherits from A and B.
C++ doesn't explicitly have interfaces, the equivalent of an interface in Java is usually implemented with a class having only pure virtual functions (plus constructors, destructor, copy assignment):
#include <iostream>
// interface
class Fooable {
public:
virtual int foo() = 0;
virtual ~Fooable() {}
};
// base class
class Base {
public:
void non_virtual_function() { std::cout << "Base::non_virtual_function\n"; }
virtual void virtual_function() { std::cout << "Base::virtual_function\n"; }
};
// derived class, inherits from both Base "class" and Fooable "interface"
class Derived: public Base, public Fooable {
public:
virtual int foo() {
// call base class function
Base::non_virtual_function();
// virtual call to function defined in base class, overridden here
virtual_function();
}
virtual void virtual_function() {
// call base class implementation of virtual function directly (rare)
Base::virtual_function();
std::cout << "Derived::virtual_function\n";
}
void non_virtual_function() {
// not called
std::cout << "Derived::non_virtual_function\n";
}
};
int main() {
Derived d;
d.foo();
}
Not sure what you're asking:
class A
{
public:
void method();
};
class B
{
public:
void method();
};
class C : public A, public B
{
public:
void callingMethod();
};
void C::callingMethod()
{
// Here you can just call A::method() or B::method() directly.
A::method();
B::method();
}
Note that multiple inheritance can lead to really hard-to-solve problems and I would recommend to only use it when necessary.
The question as stated,
C++ is it possible to make a class extend one class and implement another?
does not make much sense. The answer to that is just "yes". You can derive from any number of classes: C++ fully support multiple inheritance.
So, given that the question as stated isn't really meaningful, it's at least possible that you meant to ask
C++ is it possible to make a class extend one class and thereby implement another?
The answer to this question is also yes, but it's not trivial. It involves virtual inheritance. Which is quite tricky.
Here's an example:
#include <iostream>
void say( char const s[] ) { std::cout << s << std::endl; }
class TalkerInterface
{
public:
virtual void saySomething() const = 0;
};
class TalkerImpl
: public virtual TalkerInterface
{
public:
void saySomething() const
{
say( "TalkerImpl!" );
}
};
class MyAbstractClass
: public virtual TalkerInterface
{
public:
void foo() const { saySomething(); }
};
class MyClass
: public MyAbstractClass
, public TalkerImpl
{};
int main()
{
MyClass().foo();
}
The virtual inheritance ensures that there is only one sub-object of type TalkerInterface in a MyClass instance. This has some counter-intuitive consequences. One is that "inheriting in an implementation" works, and another is that construction of that base class sub-object happens down in each MyClass constructor, and more generally down in the most derived class.
Cheers & hth.,