Gtest per test tear down after fixture destructor - c++

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.

Related

Ignore method calls inside constructor for testing constructor method with Mockito and Junit4

how are you?
I'm trying to implement an unitary test for a class constructor. I can't modify the code of the class i'm testing.
The scenario i'm dealing with looks like this:
The class
public ClassIWantToTest{
//Class constructor
public void ClassIWantToTest(){
...
methodA();
...
methodB();
...
}
public void methodA(){
//do something...
}
public void methodB(){
//do something...
}
}
The test
#Test
public void testForConstructor(){
Atribute1 atb1 = mock(...);
Atribute2 atb2 = mock(...);
ClassIWantToTest c = new ClassIWantToTest();
doNothing().when(c).methodA();
doNothing().when(c).methodB();
assertEquals("atb1",atb1);
assertEquals("atb2",atb2);
...
}
methodA() and methodB() are void. I want to ignore them and just check if the atributes got correctly inserted in the class object instance I've created. I can't figure out how to do this since methodA and methodB are called in the constructor and I cant test the constructor without calling it. I also can't call "doNothing()" for methodA() and methodB() since an ClassIWantToTest mock needs to be created for the "doNothing()" call.
I tried to create a ClassIWantToTest mock and use "doCallRealMethod()" for the constructor test, but I cant call the constructor method for mocked object instances.
I would be grateful if someone could help me.
I tried to create a ClassIWantToTest mock and use "doCallRealMethod()" for the constructor call(since I want to test this call) and use "doNothing()" for the methodA() and methodB() calls, but I cant call the constructor method for mocked object instances. Doing this I wanted to call the constructor method and ignore the methodA() and methodB() with the doNothing().

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.

Can I initialize references in a class? (perhaps in the constructor?)

I am a bit rusty on my C++, and in particular with references.
I have an old code, something like
TEST(SomeTest,someFunction){
AClass anObject= GetSomeObject();
ASingletonClass &aReference= ASingletonClass::GetInstance();
//... some more code
}
For reasons of design I have to rewrite this code, and this time I have to use an auxiliary class (*)
class ASingletonClassFixture: public testing:Test{
public:
void SetUp() override
{
anObject=GetSomeObject();
aReference= ASingletonClass::GetInstance();
}
protected:
AClass anObject;
ASingletonClass &aReference; //<--I don't think this is correct
}
I think that the above code is not correct because references should be initialized when created.
So my question is how can I do something like this? Can I do it in the constructor?
(*) The reason if you are interested -although not essential to know- is because I am writing a test fixture.
Yes, you can do it in the test constructor - and it is even the recommended way:
class ASingletonClassFixture: public testing::Test{
public:
ASingletonClassFixture() : aReference{ASingletonClass::GetInstance()} {}
void SetUp() override
{
anObject=GetSomeObject();
}
protected:
AClass anObject;
ASingletonClass &aReference; //<--I don't think this is correct
};
see this FAQ.
However, be mindful that even though constructor and SetUp are called before each test body (the order is always ctor, SetUp, test body, TearDown, dtor), given you're using a singleton - it will be initialized only once and it's state will be shared between the test cases! What is more, if you have more test suites in the same test binary, as the singleton is most probably implemented as a static object, it will be initialized once for the whole test binary and deinitialized once the main method of the binary exits.

Using GMock to verify a Destructor Call

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.

C++ Base class destrutor order problem

Does anyone know any trick I could use to keep the Derived class until the base class destructor have been called?
i.e:
#include <iostream.h>
class Base
{
public:
Base(){ cout<<"Constructor: Base"<<endl;}
virtual ~Base(){ cout<<"Destructor : Base"<<endl;}
};
class Derived: public Base
{
//Doing a lot of jobs by extending the functionality
public:
Derived(){ cout<<"Constructor: Derived"<<endl;}
~Derived(){ cout<<"Destructor : Derived"<<endl;}
};
void main()
{
Base *Var = new Derived();
delete Var;
}
This will result in Derived class to be destroyed, then Base class will be destroyed.
The reason I need something like this is I have a custom Event(signal/slot) class.
The Event class provide an Observer class.
If I define :
class A : public Event::Observer
and then delete an instance of class A, when the ~Observer automatically remove any signal connected to this observer.
But since Class A is destroyed before the Observer, if something on a different thread call a slot on A after ~A and before ~Observer get called. Everything goes to hell...
I can always call the Observer.release method from the ~A, which fix the timing issue. But it was cleaner if I wouldnt need to.
Any ideas?
You definitely don't want to change destruction order, which is good, because you can't.
What you really want to do is to dispose/disconnect/shutdown the Observer.
What I would do is add this to your Event::Observer class:
void Event::Observer::Shutdown()
{
if(!isShutdown)
{
//Shut down any links to this observer
isShutdown = true;
}
}
void ~Event::Observer()
{
Shutdown();
//rest of Event::Observer destruction
}
and then:
~A()
{
Shutdown();
//clean up any other A resources
}
If you did something like IDisposable suggested by David, that would work too -- just call Observer::Dispose() in your destructor for class A.
My code all assumes that you have only a single thread accessing these objects. Thread synchronization is an entirely separate subject.
Destructors work as they are expected to do and you should not touch them (actually, you can't change the calling order). As for your task - you need proper threads synchronization. As a simplest solution: unsubscribe your observer before deleting it.
I suggest you either implement reference counting or an IDisposable interface and use it as a convention amongst your clients. Whether or not you call Observer::Release() in your A::dtor(), YOu're talking about having a different thread come in and call a method on an object that is being destroyed. That is definitely a race condition, you should never have code from another thread asynchronously executing on a method on an object that is being destroyed.
With reference counting, the event subscriber objects don't get deleted until they are unregistered. With an IDisposable pattern, you make sure to remove any references to an object before the destructor is called. Either could be appropriate depending on your architecture.
Base class destructor always gets called after derived class destructor. You mustn't call any of object's methods from other threads after object's destructor begins execution (regardless of whether it has a base class or not). I'd suggest using a new class that works as a container for class Base instances and implements a safe access to Base's objects (you probably need to use one of synchronization objects to implement id).
You cannot change the order of destruction in an inheritance relationship and that's good (what would a Derived be once its Base was destroyed?. However, you can change the relationship.
For example you could always wrap Derived in a class (template) which calls release() first before destroying Derived.
It's a typical race condition, it's just that this one is glaring.
There are obviously several methods at your disposal. You could for example have a mutex in the Base class and lock it as soon as you enter the destructor of the most derived class... however as you noted it's difficult.
I would suggest making the destructor protected (for each class in the hierarchy) and have a method to invoke for destruction (objects cannot be allocated on the stack any longer), then overload delete for the Base class, and have it unregister your object first before destroying it by calling this special method.
The only issue is that anyone not respecting the make your destructor protected bit will screw things up.
On the other hand, you could also NOT use inheritance, and prefer composition instead. This would allow you to control the destruction order of the various attributes.