Google Mock: leaked mock object found at program exit?
When I define my test as follows it works.
TEST(MyService, WhenCalled_DoesTheRightThingTM) {
// Arrange
ThirdPartyClassFake stub;
EXPECT_CALL(stub, GetFirstName())
.WillRepeatedly(Return("Bob"));
// Act
std::string result = stub.GetFirstName();
// Assert
EXPECT_STREQ("Bob", result);
}
ThirdPartyClassFake is a google mock class I created.
When I add code that passes a pointer to my stub to a wrapper class I get a leaked memory error:
TEST(MyService, WhenCalled_DoesTheRightThingTM) {
// Arrange
ThirdPartyClassFake stub;
EXPECT_CALL(stub, GetFirstName())
.WillRepeatedly(Return("Bob"));
// Act
MyWrapperClass wrapper(&stub);
std::string result = stub.GetFirstName();
// Assert
EXPECT_STREQ("Bob", result);
}
The error is:
1> [ RUN ] MyService.WhenCalled_DoesTheRightThingTM
1>unknown file : error : SEH exception with code 0xc0000005 thrown in the test body.
1> [ FAILED ] MyService.WhenCalled_DoesTheRightThingTM (1 ms)
1>c:\myfile.cpp(17): error : this mock object (used in test
MyService.WhenCalled_DoesTheRightThingTM) should b开发者_开发知识库e deleted but never is.
Its address is @0028E40C.
1>EXEC : error : 1 leaked mock object found at program exit.
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5):
error MSB3073: The command "C:\MyProject.Tests.exe
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5):
error MSB3073: :VCEnd" exited with code 1.
Not sure if it's relevant but I should add that ThirdPartyClassFake
subclasses from a 3rd party abstract class (which I have no control over) with all virtual methods but no virtual destructor. Also it is declared with the Microsoft-specific attribute __declspec(novtable)
.
I thought the issue might be with the lack of a virtual destructor as described in the Google Mock FAQ. However I believe if that was the issue the first test should fail too.
How do I fix/workaround this error?
0xc0000005 is Access Violation, from memory. What's likely is that this SEH exception was thrown and the destructor wasn't called properly if you didn't compile the code with the right switches.
I think I have traced the error to the destructor of MyWrapperClass
which calls a global/static function Destroy
(3rd party) on the object passed into the constructor. Since the object I pass in is a fake, it probably causes Destroy
to fail for one reason or another. So the question is how do I work around this? In this case, MyWrapperClass
is the object under test so I do not want to modify it or mock it out. I guess I have to find a way to mock the function Destroy
. Will report back if I find out how.
精彩评论