Using GMock to verify a Destructor Call - c++

Using GMock, how can I verify that a class's destructor is called? Is there a way, other than to wrap it in another class?
The obvious method, EXPECT_CALL(object, ~classtype()) yields a compiler error (gmock cannot produce a mock method called gmock_~classtype).

An easy way to check for a destructor call:
class MockFoo : public Foo {
...
// Add the following two lines to the mock class.
MOCK_METHOD0(Die, void());
virtual ~MockFoo() { Die(); }
};
In your test function:
MockFoo* foo = new MockFoo;
...
{
EXPECT_CALL(*foo, Die());
}
More Details can be found here:
Mocking Destructors

Unless you're passing --gmock_catch_leaked_mocks=0, then gmock should already be detecting when you fail to destroy a mock. The destructor is where unsatisfied expectations are flagged as errors, so gmock has special support for detecting when it is not called.

Related

Google mock with unique_ptr object giving memory leak issue

I am new to Google Test.
I have one base class and derived class with calling class
class Base
{
public:
virtual ~Base() {}
virtual int target_method() = 0;
}
class DerivedClass : public Base
{
public:
virtual ~DerivedClass () {}
int target_method() override;
}
class CallingClass
{
public:
CallingClass(std::unique_ptr<DerivedClass> _drivedClass);
private:
std::unique_ptr<DerivedClass> drivedClass;
}
From my Test:
class MockDerivedClass : public DerivedClass
{
public:
MOCK_METHOD0(target_method, int());
}
TEST(TestGroup, Test1)
{
std::unique_ptr<MockDerivedClass> mockClass(new MockDerivedClass());
EXPECT_CALL(*mockClass, target_method()).WillRepeatedly(Return(1));
CallingClass callingClass(std::move(mockClass));
callingClass.callSomthing();
EXPECT_EQ(_ , _);
}
The test is running fine and the mock method is being called as expected. At the end of test I am getting this error:
ERROR: this mock object (used in test TestGroup.Test1) should be deleted but never is. Its address is #0x5585d93e4770.
ERROR: 1 leaked mock object found at program exit. Expectations on a mock object is verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock.
Is there anything can be done at end of test to suppress this or to resolve this?
By using a uniqe_ptr, the owner of the mock object becomes the CallingClass. The leak detection expects mockClass to be destructed within your TEST, not possibly after that.
Note that gMock will verify the expectations on a mock object when it is destructed. See this reference.
You can either avoid using a unique pointer and construct the mock object in your test and just pass its address to your CallingClass, or add this at the end of your test:
EXPECT_TRUE(Mock::VerifyAndClearExpectations(mockClass.get()));
This verifies and removes the expectations on mockClass and returns true if and only if successful.

Mocking a parameterized constructor using powermockito

Consider the code given below:
#Override
public void A() {
objectA = objectB.B();
objectA.C(someValue);
objectC = new constructor(objectA,callback());
//Rest of the code
}
}
public Callback callback() {
return new callback() {
#Override
public void someMethod(someArgument) {
//some Code
}
};
}
I am trying to write a unit test case where:
the call objectB.B() has to be mocked
the call to the constructor has to be mocked
This is what I have done using Mockito and Powermockito:
#InjectMocks
ClassBeingTested testObject;
#Mock
ClassB objectB;
#Mock
ClassC objectC;
#Before()
public void setup() {
when(objectB.B()).thenReturn(new ObjectA("someValue"));
whenNew(objectC.class).withArguments(any(),any()).thenReturn(objectC);
}
#Test()
public void testMethod() {
testObject.A();
}
The first mock successfully works but the second mock using whenNew fails with the following error:
org.powermock.reflect.exceptions.ConstructorNotFoundException: No constructor found in class 'ClassC' with parameter types: [ null ]
If I use withArguments(objectA, callback()) where I have the implementation of callback in my test class, the actual constructor is called.
I want to mock the constructor call and restrict the call to the actual constructor. How can I do that?
I can not edit the code design since that is out of my scope.
In short, you get the error due to usage of 2 generic any() matchers.
When you use .withArguments(...) and set both as any() it implies
.withArguments(null, null) (since any() may match pretty much anything including nulls) which folds eventually as a single null and reflection api (which PowerMock heavily relies on) fails to discover a suitable constructor for ClassC(null).
You may check out the source of org.powermock.api.mockito.internal.expectation.AbstractConstructorExpectationSetup<T>
source that does the job
To fix up the issue consider using either .withAnyArguments() if you do not care of param types and stubbing all available constructors OR specify more concrete types while using any() like so
whenNew(ClassC.class).withArguments(any(ClassA.class), any(Callback.class))

Gtest per test tear down after fixture destructor

I know that Gtest has a TearDown, but it is called before the destructor of the fixture class is called. I also know that there is the TearDownTestCase, which is called after all the tests using that fixture are executed and after the last instance of the fixture is deleted.
Are there any form of tear down that executes for each test but after the destructor of the fixture has been called?
Trying to explain the problem I want to solve with this approach. This is what the code looks like:
class c;
class MyFixture : public ::testing::Test, public A {
...
static C *c;
SetUp(){
c = new C();
SetC(c) // this function is from base class A
}
};
TEST_F(B, test1){
...
}
I don't have access to the implementation of A. What happens is that I always need to create and destroy c on each test, but if I destroy it before the destructor of base class A is called, something happens there that causes the test to exit (without any explicit error, it just exits with code 255).
The real solution is probably some fix on class A's destructor. But while I don't have it, I was wondering if there was a standard way to destroy c after each test, after the destructor of A is called.

How do I use GMock with dependency injection?

I have a class which carries a couple of dependencies which I'd like to mock using Google Mocks, in order to test the class with Google Test.
Simplified, I have the following1:
template<typename TDep>
class SUT {
private:
TDep dependency;
public:
explicit SUT(const TDep& dep) : dependency(dep) { }
SUT(const SUT& other) : dependency(dep.other) { }
// some methods that use the dependency
}
I also have an interface for the dependency,
class IDependency {
public:
virtual double calculateCoolStuff(double) const = 0;
virtual ~IDependency() { };
}
and a mock object
class MockDependency {
public:
MOCK_CONST_METHOD1(calculateCoolStuff, double(double));
};
However, when I try to compile something like
MockDependency mock;
SUT sut(mock);
I get errors stating error: use of deleted function MockDependency(const MockDependency&), i.e. there is no copy-constructor of the mocked object. I found this discussion on Google Groups which basically ends in making mock objects non-copyable, but allowing the user to add a copy constructor and define copy behavior manually. Very well:
class MockDependency {
public:
MockDependency(const MockDependency& other) { }
MOCK_CONST_METHOD1(calculateCoolStuff, double(double));
};
Now my code compiles, but if I run something like
MockDependency mock;
SUT sut(mock);
EXPECT_CALL(mock, calculateCoolStuff(2.0)).WillRepeatedly(Return(3.0));
sut.doStuff(); // Calls calculateCoolStuff
in a test, I get an error stating that the call was never set up. In other words, the instance mock which I can use to setup expectations, is no longer the same as the instance on SUT used for calculations. This makes testing with GMock and DI difficult, to say the least...
What is the best solution to this?
1) Yes, I'm using poor man's DI. Not the topic of this conversation...
You can use dependency injection with references by ensuring that your class member is a reference:
template<typename TDep>
class SUT {
private:
TDep& dependency; // Reference
// etc.
}
Note that you no longer need a copy constructor on MockDependency. As a rule, you need access to all instances of mock objects being used by your SUT to set up expectations on them.

Moq and virtual properties and methods

I'm using Moq for unit testing. It order for Moq to work, properties and methodes have to be marked as virtual. Sometimes I pass in data and set property values in the constructors. Isn't there a rule that you should not set virtual properties in constrcutors since it might cause unexpected behaviour (if the class has been inherited from a base class) or is it safe to do it?
It is, indeed a problem, and Visual Studio Code Analysis explicitly checks for this.
A simple workaround for this is to move the work to a non-virtual internal member, and then have the virtual method call that, as well as the constructor. Something like this:
public class MyClass
{
public MyClass()
{
this.DoStuffInternal();
}
public virtual void DoStuff()
{
this.DoStuffInternal();
}
internal void DoStuffInternal()
{
// Interesting stuff happens here
}
}