calveeen
calveeen

Reputation: 651

Compare enum types

I am implementing some unit test using cpp unit test framework for visual studio. I want to be able to compare enums in the test but there is always an error that keeps showing up.

This is the code that causes me the error.

ClauseEntities ent1 = varMap.at("a");
ClauseEntities ent2 = varMap.at("v");

Assert::AreEqual(ent1, ASSIGN_STATEMENT);
Assert::AreEqual(ent1, VARIABLE);

ent1 is a enum state and ASSIGN_STATEMENT is also an enum state from the same enum.

Severity    Code    Description Project File    Line    Suppression State
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<enum ClauseEntities>
(const enum ClauseEntities &).  
UnitTesting C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\VS\UnitTest\include\CppUnitTestAssert.h 66  

Not sure how i am supposed to create a template specialisation for to string of enums..

Upvotes: 1

Views: 1835

Answers (2)

Marek R
Marek R

Reputation: 37607

This is quite simple

namespace Microsoft {
namespace VisualStudio {
namespace CppUnitTestFramework { // not sure if namespaces are actually needed

std::wstring ToString(ClauseEntities value)
{
    switch (value) {
    case ClauseEntities::ValueA: return L"ValueA"; //assuming that you are using enum class
    case ClauseEntities::ValueB: return L"ValueB";
    }

    return std::to_wstring(static_cast<int>(value));
}

} // namespace CppUnitTestFramework 
} // namespace VisualStudio
} // namespace Microsoft

Upvotes: 2

Hawky
Hawky

Reputation: 440

I have never used microsoft cpp unit tests, but from the error message and experience with gtests I think you have to add a method ToString for your enum class. (My guess is) It is because if the Assert fails, both arguments are printed to some output using ToString method.

At the end of this article similar problem is solved.

Upvotes: 3

Related Questions