0

我正在尝试使用turtle和boost创建一个带有模拟对象的单元测试。但是该示例不起作用,我找不到错误。我希望没有错误,但结果是:

$ ./unittest 
Running 1 test case...
Start
Display: 0
End
Calculator.spec.cpp(16): error in "zero_plus_zero_is_zero": untriggered expectation: v.MockView::display
. once().with( 0 )

计算器.h:

#ifndef CALCULATOR_H
#define CALCULATOR_H

#include "View.h"

class Calculator {
public:
    Calculator(View& v);

    void add( int a, int b ); // the result will be sent to the view 'v'
private:
    View& view;
};

#endif //CALCULATOR_H

计算器.cpp:

#include "Calculator.h"

Calculator::Calculator(View& v)
: view(v) {}

void Calculator::add(int a, int b) {
    view.display(a + b);
}

视图.h:

#ifndef VIEW_H
#define VIEW_H

class View {
public:
    View() = default;

    void display(int a);
};

#endif //VIEW_H

查看.cpp:

#include "View.h"
#include <iostream>

void View::display(int a) {
    std::cout << "Display: " << a << std::endl;
}

计算器.spec.cpp:

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE calculator
#include "Calculator.h"
#include "View.h"
#include <turtle/mock.hpp>
#include <boost/test/unit_test.hpp>

MOCK_BASE_CLASS(MockView, View) {
    MOCK_METHOD(display, 1)
};

BOOST_AUTO_TEST_CASE( zero_plus_zero_is_zero ) {
    std::cout << "Start" << std::endl;
    MockView v;
    Calculator calculator(v);
    MOCK_EXPECT(v.display).once().with(0);
    calculator.add(0, 0);
    std::cout << "End" << std::endl;
}

生成文件:

    test: Calculator.spec.cpp Calculator.cpp Calculator.h View.cpp View.h
        g++ Calculator.spec.cpp Calculator.cpp View.cpp -o unittest --std=c++11 -lboost_unit_test_framework

当我将测试更改为时,单元测试不会产生错误

BOOST_AUTO_TEST_CASE( zero_plus_zero_is_zero ) {
    std::cout << "Start" << std::endl;
    MockView v;
    Calculator calculator(v);
    MOCK_EXPECT(v.display).once().with(0);
    //calculator.add(0, 0);
    v.display(0);
    std::cout << "End" << std::endl;
}

我想念什么?我的测试问题出在哪里?

4

1 回答 1

1

您的模拟对象是的子类,View它定义了display. 但是因为display没有在 中声明virtualView所以基类版本是从单元测试而不是模拟版本中调用的。您可以观察到这一点,因为Display: 0它存在于单元测试的输出中。定义View::displayvirtual,它将起作用。

于 2018-01-18T18:56:31.133 回答