简体   繁体   English

使用Qt进行单元测试:更改测试功能中使用的StandardPath

[英]Unit tests with Qt: change StandardPaths used in tested functions

I'm writing unit tests for a function in Qt. 我正在为Qt中的功能编写单元测试。

My Code 我的密码

I have a function that I want to test: 我有一个要测试的功能:

QSqlDatabase createDB() {
    QString database = "library";
    QString dbPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    QDir appDataDir(dbPath);
    if (!appDataDir.exists()) {
        appDataDir.mkpath(dbPath);
    }
    dbPath += "/" + database + ".sqlite";
    QSqlDatabase db;
    db.setDatabaseName(dbPath);
    return db;
}

So in my test I have: 所以在我的测试中,我有:

void DatabaseManagerTest::initTestCase()
{
    QStandardPaths::setTestModeEnabled(true);
}

void DatabaseManagerTest::testDb()
{
    QSqlDatabase m_db = createDb();
    QString database = "library";
    QString databasePath_exp = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)
    + "/" + database + ".sqlite";

    QCOMPARE(m_db.databaseName(), databasePath_exp);
    qDebug() << m_db.databaseName();
}

QTEST_MAIN( DatabaseManagerTest )

The output of the test is 测试的输出是

1: FAIL!  : DatabaseManagerTest::testDb() Compared values are not the same
1:    Actual   (m_db.databaseName()): "/home/olivier/.local/share/MyTest/library.sqlite"
1:    Expected (databasePath_exp)   : "/home/olivier/.qttest/share/MyTest/library.sqlite"

The Question 问题

How can createDb() use the test StandardPaths of Qt and not the real ones? createDb()如何使用Qt的测试标准路径而不是真实的?

A test should never use global variables, and "QStandardPaths::writableLocation" is a wrapper for a global variable. 测试永远不要使用全局变量,并且“ QStandardPaths :: writableLocation”是全局变量的包装。 I don't think you can get out of this without injecting this dependency: you may: 我认为如果不注入这种依赖关系,您将无法摆脱困境:您可能会:

  • have "createDB()" to take the first part of path as a string parameter 具有“ createDB()”以将路径的第一部分作为字符串参数
  • have "createDB()" to take a parameter of an abstract class 'pathLocator' with a virtual function 'getBasePath'. 具有“ createDB()”以使用虚拟函数“ getBasePath”获取抽象类“ pathLocator”的参数。 Production code will use a concrete child that returns "/home/olivier/.local/share/" while the test will use a mock child that returns "/home/olivier/.qttest/share/" 生产代码将使用返回“ /home/olivier/.local/share/”的具体子代,而测试将使用返回“ /home/olivier/.qttest/share/”的模拟子代

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM