How do I mock the following code?
class ISomeClass
{
public:
virtual ~ISomeClass() {} = 0;
virtual const MyType & getType() const = 0;
virtual MyType & getType() = 0;
};
I have tried the following, but it doesn´t work. Can you please help me?
class MockSomeClass : public ISomeClass
{
public:
using MyTypeConstRefType = const MyType&;
using MyTypeRefType = MyType&;
public:
MOCK_METHOD0(getType, MyTypeConstRefType(void) const);
MOCK_METHOD0(getType, MyTypeRefType(void));
};
const member functions may be invoked for const and non-const objects. non-const member functions can only be invoked for non-const objects. If a non-const member function is invoked on a const object, it is a compiler error.
Casting away const relies on the caller only using the function on non-const objects. A potential solution is to alter the code in // .... so that it doesn't need to use the object's "current color". Add versions of all the functions you use, that take a QColor parameter instead.
There are legitimate uses of having two member functions with the same name with one const and the other not, such as the begin and end iterator functions, which return non-const iterators on non-const objects, and const iterators on const objects, but if it's casting from const to do something, it smells like fish.
They provide a separate set of macros for const
member functions ("methods"): MOCK_CONST_METHOD#
. So in your case, it would be:
MOCK_CONST_METHOD0(getType, MyTypeConstRefType());
The usage is otherwise identical to MOCK_METHOD#
, taking the function name in the first argument and function type in the second.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With