我正在为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的测试标准路径而不是真正的测试?
答案 0 :(得分:1)
测试永远不应该使用全局变量,并且&#34; QStandardPaths :: writableLocation&#34;是全局变量的包装器。 我不认为你可以摆脱这种依赖而不注入这种依赖:你可以: