Yue Wang
Yue Wang

Reputation: 1750

How to compare two iterators for unit test on VS2013?

code :

#include "stdafx.h"
#include "CppUnitTest.h"
#include <vector>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace unit_test
{
    TEST_CLASS(test_iterator)
    {
    public:

        TEST_METHOD(vector_with_int)
        {
            std::vector<int> samples;
            Assert::AreEqual(samples.begin(), samples.begin());
        }

    };
}

When compiling :

Error 1 error C2338: Test writer must define specialization of ToString for your class class std::basic_string,class std::allocator > __cdecl Microsoft::VisualStudio::CppUnitTestFramework::ToString > >>(const class std::_Vector_iterator > > &). c:\program files (x86)\microsoft visual studio 12.0\vc\unittest\include\cppunittestassert.h 66 1 unit_test

How to fix this problem? Should I use another framework instead?

Upvotes: 1

Views: 513

Answers (2)

evilrix
evilrix

Reputation: 172

Just add something like this before your tests:

namespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework {

   using vecint_itr = typename std::vector<int>::iterator;

   template<> inline std::wstring ToString<vecint_itr>(vecint_itr const & t)
   {
      return L"vecint_itr"; // replace with string with whatever you like
   }

}}}

This injects a ToString function into the CppUnitTestFramework, which is needed to convert your iterator into a string value that can be displayed by the testing framework. This is exactly what the error message is asking you to do.

Upvotes: 2

Paul Evans
Paul Evans

Reputation: 27577

You might want to subtract begin from each iterator (if they're random iterators) so you're comparing size_type offsets rather than iterator types:

Assert::AreEqual(samples.begin() - samples.begin(), samples.begin() - samples.begin());

Upvotes: 3

Related Questions