Class Skeleton
Class Skeleton

Reputation: 3073

C2338 compile error for a Microsoft Visual Studio unit test

I am receiving the following error when I attempt to compile a unit test in Visual Studio 2013:

Error 1 error C2338: Test writer must define specialization of ToString<Q* q> for your class class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> > __cdecl Microsoft::VisualStudio::CppUnitTestFramework::ToString<struct HINSTANCE__>(struct HINSTANCE__ *).

You can replicate the error by having a test method such as below:

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

Does anyone know how I need to go about writing such a specialization of ToString?

Upvotes: 3

Views: 8054

Answers (3)

Paul Chen
Paul Chen

Reputation: 1881

As of 2021, the answer Class Skeleton provided did not work for me, but I made some modifications based on it and the following compiled. Basically the lines that follows the error message provided some examples.

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());
}

Replace MyClass with your class.

Upvotes: 0

I had the same problem when comparing class objects. For me I could resolve it by simply writing

Assert::IsTrue(bitmap1 == bitmap2);

instead of

Assert::AreEqual(bitmap1, bitmap2);

Upvotes: 9

Class Skeleton
Class Skeleton

Reputation: 3073

I managed to resolve the issue by adding the following code into my unit test class file:

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

I based this on the contents of CppUnitTestAssert.h (which is where the compilation error occurs - double clicking on the compilation error will open this file for you).

Near the top of the file (and only a few lines down if you double clicked on the compilation error as noted above) you can see a set of ToString templates. I copied one of these lines and pasted it into my test class file (enclosed in the same namespaces as the original templates).

I then simply modified the template to match the compilation error (specifically <struct HINSTANCE__>(struct HINSTANCE__ * t)).

For my scenario, using RETURN_WIDE_STRING(t) is sufficient in displaying a mismatch in my AreSame assertion. Depending on the type used you could go further and pull out some other meaningful text.

Upvotes: 6

Related Questions