C2338编译错误的Microsoft Visual Studio单元测试

Cla*_*ton 2 c++ windows unit-testing vs-unit-testing-framework visual-studio-2013

我尝试在Visual Studio 2013中编译单元测试时收到以下错误:

错误1错误C2338:测试编写者必须为您的类类std :: basic_string <wchar_t,struct std :: char_traits <wchar_t>定义ToString <Q*q>的特化,类std :: allocator <wchar_t >> __cdecl Microsoft :: VisualStudio :: CppUnitTestFramework :: ToString <struct HINSTANCE __>(struct HINSTANCE__*).

您可以通过如下所示的测试方法来复制错误:

const std::wstring moduleName = L"kernel32.dll";
const HMODULE expected = GetModuleHandle(moduleName.c_str());
Microsoft::VisualStudio::CppUnitTestFramework::Assert::AreEqual(expected, expected);
Run Code Online (Sandbox Code Playgroud)

有谁知道我需要怎么写这样的专业化ToString

Cla*_*ton 6

我设法通过将以下代码添加到我的单元测试类文件中来解决此问题:

/* ToString specialisation */
namespace Microsoft
{
    namespace VisualStudio
    {
        namespace CppUnitTestFramework
        {
            template<> static std::wstring ToString<struct HINSTANCE__>
                (struct HINSTANCE__ * t)
            { 
                RETURN_WIDE_STRING(t);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我基于CppUnitTestAssert.h的内容(这是编译错误发生的地方 - 双击编译错误将为您打开此文件).

在文件顶部附近(如果您双击上面提到的编译错误,只有几行),您可以看到一组ToString模板.我复制了其中一行并将其粘贴到我的测试类文件中(包含在与原始模板相同的名称空间中).

然后,我只是修改模板以匹配编译错误(具体<struct HINSTANCE__>(struct HINSTANCE__ * t)).

对于我的场景,使用RETURN_WIDE_STRING(t)足以在我的AreSame断言中显示不匹配.根据使用的类型,您可以更进一步,并提取一些其他有意义的文本.


Mat*_*ler 6

比较类对象时遇到了同样的问题.对我来说,我可以通过简单的写作解决它

Assert::IsTrue(bitmap1 == bitmap2);
Run Code Online (Sandbox Code Playgroud)

代替

Assert::AreEqual(bitmap1, bitmap2);
Run Code Online (Sandbox Code Playgroud)