无法使用 CppUnitTest 框架在 Visual Studio 2019 上运行测试Microsoft



我有一个函数std::vector<Token> tokenize(const std::string& s),我想对它进行单元测试。Token结构体定义如下:

enum class Token_type { plus, minus, mult, div, number };
struct Token {
Token_type type;
double value;
}

我已经设置了CppUnitTest,可以运行1 + 1 == 2等玩具测试。但当我试图对tokenize函数进行测试时,它会给我一个错误:

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<class std::vector<struct Token,class std::allocator<struct Token> >>(const class std::vector<struct Token,class std::allocator<struct Token> > &).

我的测试代码是:

#include <vector>
#include "pch.h"
#include "CppUnitTest.h"
#include "../calc-cli/token.hpp"

using namespace std;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace test_tokens {
TEST_CLASS(test_tokenize) {
public:
TEST_METHOD(binary_operation_plus) {
auto r = tokenize("1+2");
vector<Token> s = {
Token{ Token_type::number, 1.0 },
Token{ Token_type::plus },
Token{ Token_type::number, 2.0}
};
Assert::AreEqual(r, s);
}
};
}

错误的原因是什么?我该如何修复?

使用Assert::AreEqual时,如果断言失败,框架希望能够显示描述对象的字符串。为此,它使用了模板化函数ToString,其中包括所有基本数据类型的专用化。对于任何其他数据类型,您都必须提供一个专业化,知道如何将数据格式化为有意义的字符串。

最简单的解决方案是使用不需要ToString的不同类型的断言。例如:

Assert::IsTrue(r == s, L"Some descriptive failure message");

另一种选择是创建断言所需的ToString专用化:

#include <CppUnitTestAssert.h>
namespace Microsoft {
namespace VisualStudio {
namespace CppUnitTestFramework {
template<> static inline std::wstring ToString(const std::vector<Token> &t)
{
// Write some code here to create a descriptive std::wstring
return std::wstring("My object description");
}

}
}
}

只有当我要使用相同的对象类型编写大量测试,并且我想自动描述对象时,我才会麻烦地进行专门化。

最新更新