gpt4 book ai didi

c++ - 使用 Qt : change StandardPaths used in tested functions 进行单元测试

转载 作者:行者123 更新时间:2023-11-30 05:31:35 25 4
gpt4 key购买 nike

我正在为 Qt 中的函数编写单元测试。

我的代码

我有一个要测试的函数:

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;
}

所以在我的测试中我有:

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 )

测试的输出是

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"

问题

createDb() 如何使用 Qt 的测试 StandardPaths 而不是真实的?

最佳答案

测试不应该使用全局变量,“QStandardPaths::writableLocation”是全局变量的包装器。我认为如果不注入(inject)这种依赖关系,您就无法摆脱困境:您可以:

  • 让“createDB()”将路径的第一部分作为字符串参数
  • 让“createDB()”获取带有虚函数“getBasePath”的抽象类“pathLocator”的参数。生产代码将使用返回“/home/olivier/.local/share/”的具体子项,而测试将使用返回“/home/olivier/.qttest/share/”的模拟子项

关于c++ - 使用 Qt : change StandardPaths used in tested functions 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35525444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com