不构建子目录项目中的单元测试[Qt / C ++]

时间:2018-05-14 03:47:13

标签: c++ qt unit-testing

我在Qt / C ++中有一个包含子项目的项目,我尝试使用单元测试来运行项目:

enter image description here

但是当我尝试构建项目时,我收到以下错误:

Undefined symbols for architecture x86_64:
  "vtable for MainWindow", referenced from:
      MainWindow::MainWindow(QWidget*) in tests.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "vtable for PaintScene", referenced from:
      PaintScene::PaintScene(QObject*) in tests.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[1]: *** [tests] Error 1

但是所有构造函数都被声明和定义。

paintscene

PaintScene(QObject *parent = nullptr);

PaintScene::PaintScene(QObject *parent) : QGraphicsScene(parent)
{
    /***/
}

mainwindow

MainWindow(QWidget *parent = nullptr);

MainWindow::MainWindow(QWidget *parent) : QWidget(parent)
{
    /***/
}

tests.cpp

#include <QtTest>
#include <QCoreApplication>
#include </Users/garbart/Desktop/paint/paint/mainwindow.cpp>
#include </Users/garbart/Desktop/paint/paint/paintscene.cpp>

class UnitTests : public QObject
{
    Q_OBJECT
private slots:
    void testWidth();
    void testColor();
    void testScene();
};

void UnitTests::testWidth()
{
    PaintScene *scene = new PaintScene();
    scene->setWidth(1000);
    QCOMPARE(scene->_width, 10);
    scene->setWidth(100);
    QCOMPARE(scene->_width, 100);
    scene->setWidth(-10);
    QCOMPARE(scene->_width, 100);
}

void UnitTests::testColor()
{
    QColor qc = Qt::red;
    PaintScene *scene = new PaintScene();
    scene->set_color(qc);
    QCOMPARE(scene->_color, Qt::red);

    qc = Qt::green;
    scene->set_color(qc);
    QCOMPARE(scene->_color, Qt::green);

    qc = Qt::black;
    scene->set_color(qc);
    QCOMPARE(scene->_color, Qt::black);
}

void UnitTests::testScene()
{
    MainWindow *window = new MainWindow();

    QColor test_color = window->grab(QRect(window->rect().x() + 500, window->rect().y() + 500, 1, 1)).toImage().pixelColor(0,0);
    QCOMPARE(test_color, Qt::white);
}

QTEST_MAIN(UnitTests)

#include "tests.moc"

1 个答案:

答案 0 :(得分:0)

它看起来像是一个经典的链接器错误(如果你没有向我们展示你的mainwindow.h头文件我们不能100%确定),你应该导出你的MainWindow类,如果你想在你的测试项目中使用它(在你的油漆项目之外)。

请参阅How to export a C++ class from a dll?