I have class to be mocked but it does not have a default constructor. I cannot change the source code, so is there any way to mock a parametrized constructor using Gmock
Using the Turtle interface as example, here are the simple steps you need to follow: Derive a class MockTurtle from Turtle . Take a virtual function of Turtle (while it's possible to mock non-virtual methods using templates, it's much more involved). In the public: section of the child class, write MOCK_METHOD();
Starting with Mockito version 3.5. 0, we can now mock Java constructors with Mockito. This allows us to return a mock from every object construction for testing purposes.
Mocking constructorsWith the mockConstruction you can mock calls made to the constructor. For example, we mock the constructor for the class Dog . The test code is inside a try with resources to limit the scope.
if your constructor is calling a method of its own class, you can fake the call using this API: // Create a mock for class MyClass (Foo is the method called in the constructor) Mock mock = MockManager. Mock<MyClass>(Constructor. NotMocked); // Faking the call to Foo mock.
Yes there is. Just let your Mock's constructor call the mocked class' constructor with the right arguments:
class base_class {
public:
base_class(int, int) {}
virtual int foo(int);
};
class base_mock : public base_class {
public:
base_mock() : base_class(23, 42) {}
MOCK_METHOD1(foo, int(int));
};
or even
class base_mock : public base_class {
public:
base_mock(int a, int b) : base_class(a, b) {}
MOCK_METHOD1(foo, int(int));
};
Edit after request from @Blackhex
Suppose our mocked class' constructor takes a reference to some other class it needs:
class helper2 {};
class helper {
public:
helper(helper2&) {}
/* Whatever */
};
class base2 {
public:
base2(helper &h) {}
virtual int foo(int);
};
Contrary to what I said in the comment, we do need to deal with all the helpers, unfortunately. However, that isn't too painful in this case as we do not need any of their functionality. We build simple, empty "plug" classes:
struct helper2_plug: public helper2 {};
struct helper_plug : public helper {
helper_plug() : helper(helper2_plug()) {}
};
Then, we can build the mock:
class base2_mock : public base2 {
public:
base2_mock() : base2(helper_plug()) {}
MOCK_METHOD1(foo, int(int));
};
I used struct
in my plugs just to avoid the public
.
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