I have this code.
I have a real object, that is initialized with a mock object.
When I call a method from the real object that should call a method from the mock object, it doesn't call the method from the mock object, but from the base class.
Why doesn't it calls the method from the mock object, how could I fix this?
Thanks
class Parent
{
public:
virtual bool verify() const;
};
class MockParent : public Parent
{
public:
MOCK_METHOD(bool, verify, (), (const, override));
};
class MyObject
{
public:
MyObject(Parent parent) :_parent(parent) {}
Parent parent;
};
class Testclass : ::testing::Test
{
TestClass() : mockParent(), myObject(mockParent) {}
MyObject myObject;
MockParent mockParent;
};
TEST_F(Testclass , test1)
{
// here I assume that it should call the method from the mock
EXPECT_CALL(this->myObject.mockParent, verify()).WillOnce(testing::Return(true));
//call method from myObject that calls parent.verify
}
In order for the polymorphic call to trigger, you need to pass a pointer or a reference to the base class, not the base class directly:
class MyObject
{
public:
MyObject(Parent& parent) :_parent(parent) {}
private: // members are usually private
Parent& parent;
};
this will allow you to have the proper method being called. Also, please keep in mind that Parent should outlive MyObject (so that you will avoid the dangling reference error).
Some additional notes: it's best to keep a pure virtual base class:
class ParentBase
{
public:
virtual ~ParentBase() = default;
virtual bool verify() const = 0;
};
and have both Parent and ParentMock to inferit from ParentBase. This enforces better separation of concerns - your classes will then deal with interfaces, not implementations.
Related
I have issue while trying to mock method that returns instance of abstract class with Rhino Mocks. Issue is that MammalBase constructor is invoked while stub is created and I would like to avoid that. All source code in question is locked for editing and only tests can be changed.
Eventually, base class is processing something by type attributes in constructor, and throws exception if no adequate attributes are detected. That causes a extensive logging.
My hope is to remove unnecessary logs from tests.
Is it possible to instruct Rhino Mocks not to instantiate return type (MammalBase) when it creates proxy while creating a stub?
Is explicit attribute or type setting possible for return value while Rhino creates stub for method with abstract class instance as return type?
Is avoiding constructor even possible without making stubbed method return interface?
I found that issue does not exist if:
1. Stubbed method returns array like MammalBase[],
2. Stubbed method returns derivate class like "Human" first, since no more constructors of base class are invoked.
Thanks in advance!
(Code sample)
public interface IDetermineMammalByType
{
MammalBase DetermineMammalByType(MammalBase creature);
}
public abstract class MammalBase
{
protected MammalBase()
{
CustomAttribute[] attributes = (CustomAttribute[])Attribute.GetCustomAttributes(this.GetType(), typeof(CustomAttribute));
if (!attributes.Any(x=> x as CustomAttribute != null))
{
//This causes issue
throw new Exception();
}
}
}
[CustomAttribute()]
public class Human : MammalBase { }
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct)]
public class CustomAttribute : System.Attribute
{
public CustomAttribute() { }
}
public class MammalDetector : IDetermineMammalByType
{
public MammalBase DetermineMammalByType(MammalBase creature)
{
//Some logic
return null;
}
}
//TEST
[TestMethod()]
public void DetermineMammalByTypeTest()
{
IDetermineMammalByType myTest = MockRepository.GenerateStub<IDetermineMammalByType>();
var creature = new Human();
//Here it fails while mocking method
myTest.Stub(x => x.DetermineMammalByType(creature)).Return(new Human());
}
I have read the concepts of Singleton design pattern and understood that for making a class singleton we have to do the following steps :
1)Private constructor to restrict instantiation of the class from other classes.
2)Private static variable of the same class that is the only instance of the class.
3)Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
So my class looks like this :
public class Singleton {
private static Singleton singleton =new Singleton();;
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(){
System.out.println("Creating new now");
}
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
public void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
But here how we can ensure that only one instance of Singleton is created ? Suppose I have 2 classes Singletondemo1 and Singletondemo2.
In Singletondemo1 , I am calling the getInstance() and craete an object. Same way I can do that in Singletondemo2 also.
So how we will ensure only object is created and also it is thread safe.
I have some classes:
class ClassA implements InterfaceA {
public function load(Foo $foo) {
}
}
interface InterfaceA {
public function load(InterfaceFoo $foo);
}
class Foo implements InterfaceFoo
{
}
My question is why is my ClassA::load(Foo $foo) method not compatible with my InterfaceA::load(InterfaceFoo $foo) even though class Foo implements InterfaceFoo?
I know I can write my ClassA as follows:
class ClassA implements InterfaceA {
public function load(InterfaceFoo $foo) {
if (!($foo instanceof Foo)) {
throw new Exception("InterfaceFoo must be an instance of Foo");
}
}
}
but I still am confused why the previous way doesn't work.
You can not do that because it violates the InterfaceA contract.
load method says it can work with any concrete implementation of InterfaceFoo, not only the specific one.
This is called polymorphism and is good.
You can dinamically downcast foo param in your load method to check if it's some concrete implementation like Foo.
I'm in a method of a derived class, loosely as follows:
Class Base
{
private:
int variableIWantToAccess;
}
Class Derived : public Base
{
public someMethod() {
variableIWantToAccess++; <<-----ERROR
}
How do I access the variable that's declared in the base class? I'm unable to access it because it is private.
You should declare it as protected instead of private.
Protected members of a class are accessible for the class descendants only.
Leave the field private and create a pair of protected getter / setter methods instead (for the same reasons you wouldn't expose a public field).
Class Base
{
private:
int variableIWantToAccess;
protected:
int GetVariable() { return variableIWantToAccess; }
void SetVariable(int var) { variableIWantToAccess = var; }
}
I have a question on object-oriented programming.
If there is a attribute which has different value in sub-classes. It should create a abstract accessor in the super-class, then override it in the sub-classes. Or create a protected instance variable in base-class, and assign the default value in the sub-class constructor?
Let's see the code example code:
Choice 1:
class BaseClass {
public abstract int GetFoo();
}
class SubClass {
public int GetFoo() {
return -1;
}
}
Choice 2:
class BaseClass {
protected int _foo;
public int GetFoo() {
return _foo;
}
}
class SubClass {
public SubClass() {
_foo = -1;
}
}
Or any ideas?
I would go with the first approach of providing a getter that can be overridden in the derived classes to provide a different value, instead of creating protected members in my class which are also package-private and violate the encapsulation principle.