访问实例类的变量

时间:2016-03-30 06:31:02

标签: c++ testing

首先,我为糟糕的标题命名感而道歉。我不确定如何正确地说出来。

我的问题是我有四个给定的课程,为简单起见,我称之为ABCD

  • D是一个包含大量数据的大型类。
  • C基本上是一个包含许多D s。
  • 的表格
  • B是一个单身人士,为A提供了一个实例。 B有一名成员C* c
  • A包含一个调用B来执行某些操作的方法。

我想测试D是否存储了正确的信息,通过A传递给程序。

以下是我的代码的简化版本,用于说明设置。

#include <stdexcept>
#include <string>
#include <vector>


class D {

public:

    // Greatly simplified; this class holds much more data in reality.

    std::string info {};

};


class C {

private:

    std::vector<D*> d {};

public:

    D* getD(int dNum) {
        return this->d.at(dNum);
    }

};


class B {

private:

    C* c {};
    D* d {};

    B() {
        this->c = new C();
    }

    ~B() {
        delete this->c;
    }

    B(const B&) = delete;
    B& operator=(const B&) = delete;

public:

    static B* getInstance() {
        static B instance {};  // singleton
        return &instance;
    }

    bool doSomething(const std::string& text) {
        int dNum = std::stoi(text);  // simplified
        try {
            this->d = this->c->getD(dNum);
            this->d->info += text;
            return true;
        } catch (const std::out_of_range&) {
            return false;
        }
    }

};


class A {

public:

    bool someFunction(const std::string& text) {
        return B::getInstance()->doSomething(text);
    }

};

我的测试应该看起来像这样。

void test() {
    std::string testString {"1"};
    A a {};
    a.someFunction(testString);
    // How can I test that for the 'D' object 'd', that was manipulated by the
    // call to 'someFunction', 'd.info == testString'?
}

我已经看过存根和模拟,但我不明白在这种情况下如何使用它们(我实际上从未使用它们)。

如果我的解释不清楚,请再次抱歉。我在C ++方面很弱,因此不知道如何解释。因此,即使搜索类似的问题也证明是不可能的,所以如果以前曾经问过这个问题我会道歉。

编辑:我知道我可以通过在B中实现一些getter方法来获得C来实现这一点,但我希望有另一种方法。

1 个答案:

答案 0 :(得分:-1)

您尚未显示是否正在为类指针分配内存。在a->someFunction(testString);中,a指向哪里?然后,在class BneededD = c->getD(dNum); c指向哪里?此外,您必须将第requiredD = d->at(dNum);行更改为requiredD = d.at(dNum);。请提供完整的详细信息,以便更好地了解问题。

相关问题