代码之家  ›  专栏  ›  技术社区  ›  Patrick Oscity

Unittest++:测试多个可能的值

  •  1
  • Patrick Oscity  · 技术社区  · 16 年前

    我现在正在C++中实现一个简单的光线跟踪程序。我有一个名为OrthonormalBasis的类,它从一个或两个指定向量生成三个正交单位向量,例如:

    void
    OrthonormalBasis::init_from_u ( const Vector& u )
    {
        Vector n(1,0,0);
        Vector m(0,1,0);
        u_ = unify(u);
        v_ = cross(u_,n);
        if ( v_.length() < ONB_EPSILON )
            v_ = cross(u_,m);
        w_ = cross(u_,v_);
    }
    

    TEST ( orthonormalbasis__should_init_from_u )
    {
        Vector u(1,0,0);
        OrthonormalBasis onb;
    
        onb.init_from_u(u);
    
        CHECK_EQUAL( Vector( 1, 0, 0 ), onb.u() );
        CHECK_EQUAL( Vector( 0, 0, 1 ), onb.v() );
        CHECK_EQUAL( Vector( 0, 1, 0 ), onb.w() );
    }
    

    有时它成功,有时它失败,因为向量v和w也可能有负1,并且仍然表示有效的正交基。有没有办法指定多个期望值?或者你知道另一种方法吗?

    重要的是,我要将实际值和预期值打印到标准输出,以便调试方法,使此解决方案无法完成此工作:

    TEST ( orthonormalbasis__should_init_from_u )
    {
        Vector u(1,0,0);
        OrthonormalBasis onb;
    
        onb.init_from_u(u);
    
        CHECK_EQUAL( Vector( 1, 0, 0 ), onb.u() );
        CHECK(
            Vector( 0, 0, 1 ) == onb.v() ||
            Vector( 0, 0,-1 ) == onb.v() );
        CHECK(
            Vector( 0, 1, 0 ) == onb.w() ||
            Vector( 0,-1, 0 ) == onb.w() );
    }
    
    3 回复  |  直到 16 年前
        1
  •  1
  •   Tom Smith    16 年前

    当然,如果你要测试的只是你的基础是否正交,那么这就是你需要测试的吗?

    // check orthogonality
    
    CHECK_EQUAL( 0, dot(onb.u(), onb.v));
    CHECK_EQUAL( 0, dot(onb.u(), onb.w));
    CHECK_EQUAL( 0, dot(onb.v(), onb.w));
    
    // check normality
    
    CHECK_EQUAL( 1, dot(onb.u(), onb.u));
    CHECK_EQUAL( 1, dot(onb.v(), onb.v));
    CHECK_EQUAL( 1, dot(onb.w(), onb.w));
    
        2
  •  0
  •   Dave Bacher    16 年前

    void CHECK_MULTI(TYPE actual, vector<TYPE> expected, const char* message)
    {
      for (element in expected) {
        if (element == actual) {
          // there's a test here so the test count is correct
          CHECK(actual, element);
          return;   
        }
      }
      CHECK(actual, expected);
    }
    
        3
  •  0
  •   Georg Fritzsche    16 年前

    我会使用一个实用函数或类,以便您可以执行以下操作:

    CHECK_EQUAL(VectorList(0,0,1)(0,0,-1), onb.v());
    

    考虑到这一点,对等式的解释有些奇怪,但它应该打印出您想要看到的所有值,而无需引入自定义宏。
    EQUAL 在这种情况下,自定义宏 CHECK_CONTAINS() 应该不会太难做到。

    VectorList operator() 用于将值插入包含的 Vector s、 近似 助推,分配

    基本方法:

    class VectorList {
        std::vector<Vector> data_;
    public:
        VectorList(double a, double b, double c) {
            data_.push_back(Vector(a,b,c));
        }
        VectorList& operator()(double a, double b, double c) {
            data_.push_back(Vector(a,b,c));
            return *this;
        }
        bool operator==(const Vector& rhs) const {
            return std::find(data_.begin(), data_.end(), rhs) != data_.end();
        }
    };
    
    推荐文章