尝试使用googletest测试ATL对象时出现异常

时间:2012-02-17 22:02:31

标签: atl googletest

我想使用googletest为我的COM对象编写一些单元测试。不幸的是,我在调用CreateInstance时遇到异常:0xC0000005: Access violation reading location 0x00000000

代码基本上如下所示:

MyClass.h

class ATL_NO_VTABLE CMyClass
    : public CComObjectRootEx<CComMultiThreadModel>,
    public CComCoClass<CMyClass, &CLSID_MyClass>,
    public IConnectionPointImpl<CMyClass, &IID_IMyClassListener>,
    public IConnectionPointContainerImpl<CMyClass>,
    public IDispatchImpl<MyComClass, &IID_MyComClass, &LIBID_MyLib, 1, 0>
{
    ...
}

Test.cpp的

#include "stdafx.h"
#include "gtest/gtest.h"

#include "MyClass.h"

TEST(MyClassTest, IsCreated)
{
    HRESULT hr(E_FAIL);
    CComPtr<MyComClass> lMyObject;
    hr = CMyClass::CreateInstance(&lMyObject);
    EXPECT_EQ(S_OK, hr);
}

int main(int argc, char **argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

我可以在一些现有(非测试)项目中调用CreateInstance而没有任何问题。我真的不懂COM / ATL,所以我很难搞清楚为什么我会得到这个奇怪的例外。

1 个答案:

答案 0 :(得分:1)

@Roman有正确的想法。我将以下main()放在我的Test.cpp中,一切都开始工作了:

#include "resource.h"

const IID LIBID_TestLib = {0xA5AD0596, 0x14AE, 0x43A3, {0xB2, 0x5E, 0xF7, 0xF9, 0x19, 0x93, 0xA7, 0x24}};

class CTestModule : public CAtlExeModuleT<CTestModule>
{

public:

    DECLARE_LIBID(LIBID_TestLib)
    DECLARE_REGISTRY_APPID_RESOURCEID(IDR_TEST, "{575D971E-C35B-470f-BE6B-FFB9145CCCD3}")

};

CTestModule gAtlModule;