GoogleTest Fixture for blitz++ class with arguments in constructor

假如想象 提交于 2019-12-13 02:48:06

问题


I have got a question that is related to this one: GTest fixture when constructor takes parameters?. I that question I wanted to know how to set up a GTest fixture when the tested class takes a parameter for the constructor. I tried to replicate the answer for blitz++ instead of arma, and I fail. Any clues?

The test class:

#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_;
}

The test:

#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();
}

The final test fails with

TClassTest.cpp:43: Failure
Value of: (*M.at(0)).extent(1)
Actual: 32767
Expected: 3

i.e. it seems that M1 is not allocated? Or it's gone out of scope?


回答1:


It's gone out of scope, just before SetUp is finished. You probably want:

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;
};

Another thing is that you are not supposed to include cpp files. Rename them to .h or .hpp.



来源:https://stackoverflow.com/questions/20517174/googletest-fixture-for-blitz-class-with-arguments-in-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!