我有一个与此问题相关的问题:GTest fixture when constructor takes parameters?。我的那个问题我想知道当测试类为构造函数获取参数时如何设置GTest fixture。我试图复制闪电战++而不是arma的答案,但我失败了。 有线索吗?
测试类:
#include <blitz/array.h>
#include <vector>
class TClass {
private:
std::vector<blitz::Array<double,2> * > mats;
public:
TClass(std::vector<blitz::Array<double,2> * > m_);
blitz::Array<double,2> * GetM( int which ){ return( mats.at(which) );};
};
TClass::TClass(std::vector<blitz::Array<double,2> * > m_){
mats = m_;
}
测试:
#include <gtest/gtest.h> // Include the google test framework
#include "TClass.cpp"
class TClassTest : public ::testing::Test {
protected:
int n;
int m;
std::vector<blitz::Array<double,2> * > M;
virtual void SetUp() {
n = 3;
m = 2;
blitz::Array<double,2> M1(n,m);
blitz::Array<double,2> M2(n,m);
M.push_back( &M1);
M.push_back( &M2);
T = new TClass(M);
}
virtual void TearDown() {delete T;}
TClass *T;
};
TEST_F(TClassTest, CanGetM1){
EXPECT_EQ( T->GetM(0), M.at(0) );
}
TEST_F(TClassTest, CanSeeN){
EXPECT_EQ( 3, n );
}
TEST_F(TClassTest, CanSeeM){
EXPECT_EQ( 3, (*M.at(0)).extent(blitz::firstDim) );
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
最终测试失败,
TClassTest.cpp:43: Failure
Value of: (*M.at(0)).extent(1)
Actual: 32767
Expected: 3
即。看来M1没有分配?或者它超出了范围?
答案 0 :(得分:1)
在SetUp完成之前,它已超出范围。你可能想要:
class TClassTest : public ::testing::Test
{
protected:
int n;
int m;
std::vector<blitz::Array<double,2> * > M;
virtual void SetUp() {
n = 3;
m = 2;
M.push_back( new blitz::Array<double,2>(n,m) );
M.push_back( new blitz::Array<double,2>(n,m) );
T = new TClass(M);
}
virtual void TearDown()
{
delete T;
delete M[0];
delete M[1];
}
TClass *T;
};
另一件事是你不应该包含cpp文件。将它们重命名为.h
或.hpp
。