我正试图为一个名为Client的模板类编写单元测试。无法成功编译unitTests代码。不确定如何在单元测试中同时通过class / typename T
和size_t size
参数。我已经制作了一个git-reogit clone https://github.com/BhanuKiranChaluvadi/gtest-minimal-example.git
,以防您希望在本地机器上编译并调查该问题。
#pragma once
#include <array>
namespace inputs
{
template <typename T, size_t size>
class IClient
{
public:
using ClientType = std::array<T, size>;
virtual const ClientType &getID() const = 0;
virtual bool isID(const ClientType &anotherID) const = 0;
};
template <typename T, size_t size>
class Client : public IClient<T, size>
{
public:
using ClientT = std::array<T, size>;
Client(const ClientT &ID) : ID(ID) {}
Client(const ClientT &&ID) : ID(std::move(ID)) {}
inline const ClientT &getID() const override { return ID; }
inline bool isID(const ClientT &anotherID) const override { return ID == anotherID; }
inline bool operator==(const Client &anotherClient) { return ID == anotherClient.getID(); }
private:
ClientT ID;
};
} // namespace inputs
这就是我的谷歌测试看起来像的样子
#include "gtest/gtest.h"
#include <type_traits>
#include "client.hpp"
#include <memory>
#include <utility>
#include <tuple>
using namespace inputs;
namespace inputs_test
{
template <class T, size_t size>
class ClientTest : public testing::Test
{
};
using testing::Types;
// The list of types we want to test.
typedef Types<std::pair<int8_t, std::integral_constant<std::size_t, 16>>,
std::pair<uint8_t, std::integral_constant<std::size_t, 24>>>
Implementations;
TYPED_TEST_CASE(ClientTest, Implementations);
TYPED_TEST(ClientTest, shouldReturnSetID)
{
typename TypeParam::first_type data_type;
typename TypeParam::second_type size;
// static constexpr std::size_t n = TypeParam::value;
EXPECT_TRUE(true);
}
} // namespace inputs_test
模板化的客户端类需要<int8_t, 16>
或<uint8_t, 24>
。我不知道如何传递size_t
模板参数。
test/googletest-src/googletest/include/gtest/gtest-typed-test.h:174:38: error: wrong number of template arguments (1, should be 2)
174 | typedef CaseName<gtest_TypeParam_> TestFixture;
一个可能的解决方案是编写一个ClientTest
类,该类将std::tuple
(或std::pair
(作为单个模板参数,并再次使用std::tuple_element
将其拆分为两个模板参数T
和size
。然后它将Client<T, size>
实例化为类成员。然后可以使用它来执行所需的测试:
namespace inputs_test {
template <typename Tup>
class ClientTest: public testing::Test {
using T = typename std::tuple_element_t<0, Tup>;
static constexpr std::size_t size = std::tuple_element_t<1, Tup>::value;
using ClientT = typename inputs::Client<T, size>::ClientT;
protected:
ClientTest() noexcept
: id{new ClientT{}}, client{new inputs::Client<T, size>{*id}} {
return;
}
~ClientTest() noexcept {
delete id;
delete client;
}
ClientT* id;
inputs::Client<T, size>* client;
};
typedef testing::Types<std::tuple<std::int8_t, std::integral_constant<std::size_t, 16>>,
std::tuple<std::uint8_t, std::integral_constant<std::size_t, 24>>>
Implementations;
TYPED_TEST_CASE(ClientTest, Implementations);
TYPED_TEST(ClientTest, shouldReturnSetID) {
EXPECT_EQ(this->client->getID(), *this->id);
}
}