Access Violation when using gmock and CppUnitTestFramework

423 views Asked by At

I've seen people using gmock with Microsoft's Cpp Unit Test Framework, but whenever I try to run a test (see example below) that makes use of the EXPECT_CALL macro I get an access violation during CppUnit's cleanup of the test case. If I comment out the EXPECT_CALL macro then the test executes and the assert fails since the default mock value is false.

The project is using C++20 (had to make a small edit to gmock to use std::invoke_result instead of std::result_of, but I don't think this is the source of my pain).

Any thoughts on why I would be having this issue?

Example code:

#include "CppUnitTest.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

class MockTest
{
public:
    MOCK_METHOD(bool, Foo, (), ());
};

TEST_MODULE_INITIALIZE(ModuleInitialize) {
    ::testing::GTEST_FLAG(throw_on_failure) = true;
    int argc = 0;
    wchar_t** argv = nullptr;
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::InitGoogleMock(&argc, argv);
}

TEST_CLASS(UnitTestClass)
{
public:

    TEST_METHOD(TestMocking) {
        MockTest mock;
        EXPECT_CALL(mock, Foo)
            .Times(1)
            .WillOnce(testing::Return(true));

        Assert::IsTrue(mock.Foo());
    }
};
1

There are 1 answers

0
Chris Olsen On

It's probably due to something in GoogleTest's default TestEventListener. I don't remember exactly what the issue is, but it doesn't play well with the MS test runner. I don't think you want the throw_on_failure flag set either.

I ran into the same problem and solved it by making a custom TestEventListener that does work in the MS environment. I did a write up of it here.