Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VS2012 : Error with unit test : Assert::AreEqual( object, object ) didn't work

I come to you for a strange problem when I use the Visual Studio Native Unit Test on VS 2012. I've a Coordinates class like that:

#ifndef COORDINATES_HPP
#define COORDINATES_HPP

#include <iostream>

namespace Core {
class Coordinates {
public:
    Coordinates();
    Coordinates( int x, int y );
    Coordinates( const Coordinates &copy );
    ~Coordinates();

    void operator=( Coordinates coordinates );
    void operator+=( Coordinates coordinates );
    void operator-=( Coordinates coordinates );
    Coordinates operator+( Coordinates coordinates );
    Coordinates operator-( Coordinates coordinates );
    bool operator==( Coordinates coordinates );
    bool operator!=( Coordinates coordinates );

    int getX() const { return m_x; }
    int getY() const { return m_y; }
    void setX( const int &val ) { m_x = val; }
    void setY( const int &val ) { m_y = val; }

protected:
    int m_x, m_y;
};
}

So the problem appear when I use : Assert::AreEqual( Coordinates(0,0), Coordinates(0,0) );

The error sended is : Error 1 error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const Core::Coordinates' (or there is no acceptable conversion) c:\program files (x86)\microsoft visual studio 11.0\vc\unittest\include\cppunittestassert.h 129 1 UnitTest1

Do you have an idea for fix that?

PS: Sorry for my english, is not my native language.

like image 275
Winter Avatar asked May 01 '13 03:05

Winter


2 Answers

The error received after creating your assignment operator, ie

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 Core::Coordinates &).

is related to needing to provide a way for the unit tests to print out the values it expected and received. You do this by creating a template specialization of the ToString function in the Microsoft::VisualStudio::CppUnitTestFramework namespace. For example:

namespace Microsoft{
    namespace VisualStudio {
        namespace CppUnitTestFramework {

            template<>
            static std::wstring ToString<Coordinates>(const Coordinates  & coord) {
                return L"Some string representing coordinate.";
            }

        }
    }
}

After that, the unit tests should run.

like image 124
Gage Avatar answered Nov 15 '22 20:11

Gage


Given the error message, you might try making your operator== more const friendly:

bool operator==( const Coordinates coordinates ) const;
like image 25
happydave Avatar answered Nov 15 '22 21:11

happydave