构造函数测试在toString()函数上失败

时间:2015-04-11 01:20:27

标签: c++ unit-testing constructor tostring

这些是我头文件中的构造函数:

CTree(char ch); 

CTree(char ch, CTree *kidsVal, CTree *sibsVal, CTree *prevVal);

这些是我的实现:

//constructor
CTree::CTree(char toAdd, CTree *kidsVal, CTree *sibsVal, CTree *prevVal) { 
    data = toAdd; 
    kids = kidsVal; 
    sibs = sibsVal; 
    prev = prevVal; 
}

//constructor
CTree::CTree(char ch) {
    data = ch;
    kids = NULL;
    sibs = NULL;
    prev = NULL;
}

这是我头文件中的toString():

std::string toString();

这是我的toString()实现:

//toString
std::string CTree::toString() { 
    std::string str;
    std::ostringstream oss; 

    oss << "\n"; 
    oss << data; 

    if (kids != NULL) { 
        oss << kids->toString(); 
    } 

    if (sibs != NULL) { 
        oss << sibs->toString(); 
    } 

    return oss.str();
} 

这是CTreeTest在第一次测试中失败的地方:

static void constructorTest() {

        // build a few trees with constructor

        CTree t1('A');

        assert(t1.toString() == "A\n");

        CTree t2('b');

        assert(t2.toString() == "b\n");

        CTree t3('^');

        assert(t3.toString() == "^\n");

    }

无法弄清楚原因。

1 个答案:

答案 0 :(得分:0)

编辑:以下程序(我认为与您的类似)在传递断言方面没有任何问题。

#include <iostream>
#include <cassert>
#include <sstream>

class CTree {
  public: 
      CTree(char c) : data(c) {}

      std::string toString() {
          std::ostringstream oss;
          oss << data;
          oss << '\n';

          return oss.str();
      }

  private:
      char data;
};

int main() {
    CTree t1('A');
    assert(t1.toString() == "A\n"); //passes assertion
    std::cout << t1.toString();

    return 0;
 }