Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NiceMock a Mock that has another Mock as a constructor parameter

I want to use a Mock with a NiceMock. The Mock has one constructor that takes another Mock as an argument. This is a small example of code that I have that works

class ClassA
{
    ClassA() { }
};

template <class T>
class ClassB>
{
    ClassB(ClassA & a) { } // constructor, no default constructor for this class
};

class ClassC
{
    ClassC() { }
};

class MyTest : public Test
{
    MockClassA a;
    MockClassB<ClassC> * b = NULL;

    SetUp()
    {
        b = new MockClassB<ClassC>(a);
    }
    ...
};

That works fine, but if I try use MockClassB with a NiceMock like this

MockClassA a;
NiceMock<MockClassB<ClassC>> * b = NULL;

SetUp()
{
    b = new NiceMock<MockClassB<ClassC>>(a);
}

I get a compile error saying cannot convert argument 1 from 'const MockClassA' to 'ClassA &'. Note that the error is on ClassA, which is the type of the argument to the constructor for ClassB. It doesn't help to wrap ClassA in a NiceMock like NiceMock<MockClassA> a, I just get a similar error: cannot convert argument 1 from 'const testing::NiceMock<MockClassA>' to 'ClassA &'

I have other templated classes that I'm using with NiceMock that work, but they don't have any constructor parameters.

Any ideas?

like image 807
Martin Avatar asked Sep 08 '17 20:09

Martin


Video Answer


1 Answers

The argument in ClassB constructor is a non-const reference to ClassA, which is not allowed in NiceMock. According to documentation, one of the limitation is:

The constructors of the base mock (MockFoo) cannot have arguments passed by non-const reference

To make it work, pass a const reference instead

ClassB(const ClassA & a) { }

or pass a pointer to ClassA

ClassB(ClassA * a) { }
like image 175
mcchu Avatar answered Oct 05 '22 23:10

mcchu