我正在尝试在Swift中进行测试。
我想测试我的代码以打开和访问SQLite数据库。我以为可以将测试SQLite文件放在测试目标中(我怀疑是问题所在)。
我能够打开数据库并返回指向我的数据库的指针(在测试包中)
func openDatabase(_ databasePath: String) -> OpaquePointer? {
var db: OpaquePointer? = nil
if sqlite3_open(databasePath, &db) == SQLITE_OK {
print("Successfully opened connection to database at \(Constants.dbName)")
return db
} else {
print("Unable to open database. Verify that you created the directory described " +
"in the Getting Started section.")
return nil
}
}
但是我无法真正读取数据库:
func readQuestionsFromDB(_ dbpointer: OpaquePointer) -> [Question] {
let querySql = "select * from Questions;"
var sqliteStatement: OpaquePointer? = nil
var questions = [Question]()
if sqlite3_prepare_v2(dbpointer, querySql, -1, &sqliteStatement, nil) == SQLITE_OK {
// does not execute
}
sqlite3_finalize(sqliteStatement)
return nil
}
运行以下测试:
func testReadDatabase() {
let sq = SQLiteManager()
let db = sq.openDatabase("sociologydb")
let test = sq.readQuestionsFromDB(db!)
XCTAssertEqual(test.count, 1) // returns zero even when the code above is correctly filled in to populate the array
}
我想这是因为我的主要目标无法访问Test目标中的资源。那么测试打开数据库代码的最佳方法是什么?