Search code examples
assertstdvectormicrosoft-cpp-unit-test

How to assert if two vectors are equal in CppUnitTest framework


I am trying to assert 2-D vectors as shown below

TEST_METHOD(TestCase1)
{
    std::vector<int> arr{2};
    int sum{ 2 };
    std::vector<std::vector<int>> subsets;
    std::vector<std::vector<int>> expected{ {2} };
    generate_subsets(subsets, arr, sum);
    Assert::AreEqual<std::vector<std::vector<int>>>(subsets, expected);
}

But it shows an error as below

Error - C2338 Test writer must define specialization of ToString<const 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<class std::vector<class std::vector<int,class…

Any suggestion would be of great help.


Solution

  • Assert::AreEqual wants to convert the values to std::wstring for display in case of failure i.e:

    Assert failed. Expected:<some value> Actual:<some other value>
    

    the compiler complains because there is no built in conversion for the type you're using.

    A quick fix would be to use Assert::IsTrue instead, since it won't try to convert the values to strings:

    Assert::IsTrue(subsets == expected, L"Unexpected value for <subsets>);
    

    If you are going to be comparing these types a lot and want Assert::AreEqual to show the actual values when a test fails, then you can do what the compile message suggests and create a ToString override for that specific type:

    #include <CppUnitTestAssert.h>
    
    namespace Microsoft {
        namespace VisualStudio {
            namespace CppUnitTestFramework {
                template<> static inline std::wstring ToString(const std::vector<std::vector<int>> &object)
                {
                    // Insert some code here to convert <object> to wstring
                    return std::wstring();
                }
            }
        }
    }