考虑下面的测试,它只需要两个数字并测试它们的总和是否等于5。
struct IntHolder
{
int x;
int y;
char* arr;
IntHolder(int x, int y)
:x(x), y(y)
{
arr = new char[3] {1, 2, 3};
}
~IntHolder()
{
delete[] arr;
}
};
class TestSum : public ::testing::TestWithParam<IntHolder> {};
TEST_P(TestSum, SumsEqualToTest)
{
EXPECT_EQ(5, GetParam().x + GetParam().y);
}
INSTANTIATE_TEST_CASE_P(SumInputs, TestSum, ::testing::Values(
IntHolder(4, 1),
IntHolder(1, 2)
));
没有char * arr,此测试正常运行,并且使用struct似乎是在拥有一个以上参数时在Google Test中使用值参数化测试的唯一方法。
但是,如果该结构需要使用new初始化任何元素(在本例中为arr),则会发生段错误,因为似乎析构函数的调用次数比构造函数多得多(这是通过调试找到的)。
为什么会这样?有没有更好的方法在Google Test中进行多值参数化测试?请注意,我没有使用C ++ 11。
修改
谢谢,正确的代码是:
struct IntHolder
{
int x;
int y;
char* arr;
IntHolder(int x, int y)
:x(x), y(y)
{
arr = new char[3] {1, 2, 3};
}
IntHolder(const IntHolder& that)
:x(that.x), y(that.y)
{
arr = new char[3] {
that.arr[0],
that.arr[1],
that.arr[2],
};
}
IntHolder& operator=(const IntHolder& that)
{
x = that.x;
y = that.y;
arr[0] = that.arr[0];
arr[1] = that.arr[1];
arr[2] = that.arr[2];
return *this;
}
~IntHolder()
{
delete[] arr;
}
};
class TestSum : public ::testing::TestWithParam<IntHolder> {};
TEST_P(TestSum, SumsEqualToTest)
{
EXPECT_EQ(5, GetParam().x + GetParam().y);
}
INSTANTIATE_TEST_CASE_P(SumInputs, TestSum, ::testing::Values(
IntHolder(4, 1),
IntHolder(1, 2)
));