【问题标题】:C2338 compile error for a Microsoft Visual Studio unit testMicrosoft Visual Studio 单元测试的 C2338 编译错误
【发布时间】:2015-04-28 16:14:13
【问题描述】:

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

错误 1 ​​错误 C2338:测试编写者必须为您的类定义 ToString 的特化 class std::basic_string,class std::allocator > __cdecl Microsoft::VisualStudio::CppUnitTestFramework::ToString(struct HINSTANCE__ *)。

您可以通过以下测试方法复制错误:

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

有人知道我需要如何编写ToString 这样的专业吗?

【问题讨论】:

    标签: c++ windows unit-testing visual-studio-2013 vs-unit-testing-framework


    【解决方案1】:

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

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

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

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

    然后我简单地修改了模板以匹配编译错误(特别是&lt;struct HINSTANCE__&gt;(struct HINSTANCE__ * t))。

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

    【讨论】:

    • 2020 年仍然出现此错误。这没有帮助:(
    【解决方案2】:

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

    Assert::IsTrue(bitmap1 == bitmap2);
    

    而不是

    Assert::AreEqual(bitmap1, bitmap2);
    

    【讨论】:

      【解决方案3】:

      截至2021年,Class Skeleton提供的答案对我不起作用,但我在此基础上进行了一些修改并编译了以下内容。基本上,错误消息后面的行提供了一些示例。

      template<>
      inline std::wstring __cdecl Microsoft::VisualStudio::CppUnitTestFramework::ToString<MyClass>(const MyClass& t)
      {
          // replace with your own, here is just my example
          // RETURN_WIDE_STRING(t.ToString().c_str());
      }
      

      用你的班级替换MyClass

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-22
        • 1970-01-01
        • 1970-01-01
        • 2010-09-18
        • 2016-10-30
        • 2015-06-30
        相关资源
        最近更新 更多