【问题标题】:Can't get test to run on Visual Studio 2019 using Microsoft CppUnitTest Framework无法使用 Microsoft CppUnitTest 框架在 Visual Studio 2019 上运行测试
【发布时间】:2021-03-20 07:36:15
【问题描述】:

我有一个函数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);
        }
    };
}

是什么导致了错误,我该如何解决?

【问题讨论】:

  • ¿您是否尝试过按照编译器错误提示定义该专业化?它是打印结果所必需的。很可能还应提供operator ==
  • @user7860670 我是一名初级程序员,这是我的第一个主要 C++ 程序。恐怕我不知道专业是什么。从网上可以看到需要在Microsoft::VisualStudio::CppUnitTestFramework里面定义一个函数ToString,但是找不到正确的签名和代码。如果我看到一个例子,我应该可以。

标签: c++ visual-studio visual-studio-2019 microsoft-cpp-unit-test


【解决方案1】:

当您使用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");
            }


        }
    }
}

如果我要使用相同的对象类型编写大量测试,并且我想自动描述这些对象,我只会费力地进行专业化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多