Using Visual Studio native C++ unit testing framework with strings instead of wide strings

544 Views Asked by At

Is there a way to configure Visual Studio native C++ unit testing framework to work with std::string instead of std::wstrings ?

Assert::Equal<class T>(const T & t1,const T &t2)

requires the function

template<class T> std::wstring ToSring<class T>(const T & t) /* note the wstring here */

to be written/specialized by the test writer for the object to be tested (of type T). I already have this function:

ostream & operator<<(ostream & o, const T & t) /* note the ostream vs wostream */

I would like to re-use (build uppon a third party narrow strings library), but I don't have the wostream equivalent, and don't want to rewrite one.

What are my options ?

1

There are 1 best solutions below

0
Chris Olsen On

If your class did have the wostream method then your specialization for ToString could simply use the provided macro RETURN_WIDE_STRING:

template<> static std::wstring ToString(const Foo &t) { RETURN_WIDE_STRING(t); }

But without changing the code under test, you could write a similar macro (or function) to convert the ostream to a wstring and use it in the same way:

template<> static std::wstring ToString(const Foo &t) { RETURN_WIDE_FROM_NARROW(t); }

The new macro might look something like:

#define RETURN_WIDE_FROM_NARROW(inputValue) \
        std::stringstream ss;\
        ss << inputValue;\
        auto str = ss.str();\
        std::wstringstream wss;\
        wss << std::wstring(str.begin(), str.end());\
        return wss.str();

You can also avoid the whole ToString specialization problem by using Assert variants that don't require it:

Assert::IsTrue(t1 == t2, L"Some descriptive fail message");

This is likely to be as much or more work though, depending how much detail you want in the fail messages.