[英]Unit tests with Qt: change StandardPaths used in tested functions
I'm writing unit tests for a function in Qt. 我正在为Qt中的功能编写单元测试。
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"
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:
我认为如果不注入这种依赖关系,您将无法摆脱困境:您可能会:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.