【问题标题】:Using Visual Studio native C++ unit testing framework with strings instead of wide strings使用带有字符串而不是宽字符串的 Visual Studio 原生 C++ 单元测试框架
【发布时间】:2020-12-22 20:20:27
【问题描述】:

有没有办法将 Visual Studio 原生 C++ 单元测试框架配置为使用 std::string 而不是 std::wstrings ?

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

需要函数

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

由测试编写者为要测试的对象(类型 T)编写/专门化。我已经有了这个功能:

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

我想重新使用(建立第三方窄字符串库),但我没有 wostream 等效项,也不想重写。

我有什么选择?

【问题讨论】:

  • 我使用宏来根据需要将消息从string 转换为wstring ...然后只需使用Assert::Fail 而不是Assert::AreEqual
  • 如果没有其他解决方案,我肯定会去,我认为值得回答......

标签: c++ unit-testing visual-studio-2019 vs-unit-testing-framework


【解决方案1】:

如果您的类确实有wostream 方法,那么您对ToString 的专业化可以简单地使用提供的宏RETURN_WIDE_STRING:

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

但在不更改被测代码的情况下,您可以编写类似的宏(或函数)将ostream 转换为wstring 并以相同的方式使用它:

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

新宏可能类似于:

#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();

您还可以通过使用不需要的 Assert 变体来避免整个 ToString 特化问题:

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

不过,这可能是一样多或更多的工作,具体取决于您希望在失败消息中包含多少细节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 2012-10-09
    • 2011-11-21
    相关资源
    最近更新 更多