【问题标题】:QT Test - Variables / Objects losing valueQT 测试 - 变量/对象失去价值
【发布时间】:2016-03-05 18:24:57
【问题描述】:

我有一个 QT 项目Test.pro 并想在几个测试类中测试一些类。 Test.pro:

QT       += testlib serialport
QT       -= gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

FORMS    += ../Folder/mainwindow.ui

TARGET = main
CONFIG += console
CONFIG += testcase
CONFIG -= app_bundle

TEMPLATE = app

SOURCES += \
    tst_var.cpp

DEFINES += SRCDIR=\\\"$$PWD/\\\"

#LIBS += -L../libs -lserial

HEADERS += \
    tst_var.h

FORMS    +=     ../Folder/mainwindow.ui \         
                ...

QT       +=     gui

头文件tst_var.h:

#ifndef TST_VAR_H
#define TST_VAR_H

#include <QObject>
#include <QtTest/QtTest>
#include <QString>
#include <iostream>

using namespace std;

class tst_var: public QObject
{
    Q_OBJECT
public:
     tst_var();
private  slots:
    void initTestCase();
    void testGetName();
    void cleanupTestCase();
private:
    QByteArray varname;
};

#endif // TST_VAR_H

问题是我在哪里定义变量varname 并不重要,它总是失去他的价值。 tst_var.cpp:

#include "tst_var.h"

tst_var::tst_var(){
    QByteArray varname("test");
    cout << "varname1:" << varname.constData() << endl;
    //Output: test
}

void tst_var::initTestCase(){
    //It does not make a different if I would define varname here  
}

void tst_var::testGetName(){
    cout << "varname2:" << varname.constData() << endl;
   //Output: (nothing), so varname lose its content
}

void tst_var::cleanupTestCase(){}

我通过main 方法开始测试。 main.cpp:

#include <QtTest/QtTest>
#include "tst_var.h"

int main(int argc, char *argv[]) {
    tst_var var;
    QTest::qExec(&var);
}

所以我不知道为什么变量会失去它的价值以及如何修复它。

【问题讨论】:

    标签: c++ qt unit-testing variables testing


    【解决方案1】:

    您将 tst_var 的构造函数定义为:

    tst_var::tst_var(){
        QByteArray varname("test");
        cout << "varname1:" << varname.constData() << endl;
        //Output: test
    }
    

    问题是,您定义了一个名为 varname 的本地堆栈值,该值只能在构造函数内部访问。相反,您想实际更改课程的 varname 成员。

    改为:

    tst_var::tst_var(){
        varname = QByteArray("test");
        cout << "varname1:" << varname.constData() << endl;
        //Output: test
    }
    

    无论varname 是什么类型以及你有什么类结构,你都会遇到同样的问题:

    #include <iostream>
    
    class tst_var {
    public:
        std::string varname;
        void init() {
            std::string varname = "hey";
            std::cout<< varname <<"\n";
        }
        void test() {
            std::cout<< varname <<"\n";
        }
    };
    
    int main() {
        tst_var test;
        test.init();
        test.test();
    }
    

    输出:

    hey
    <empty line>
    

    使用相同的过程修复它可以解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多