I'm experimenting with testing in Swift.

I want to test my code to open and access an SQLite database. I thought to do this I could put a test SQLite file in my test target (which I suspect is the problem).

I am able to open the database and return a pointer to my database (in the test bundle)

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

but I'm unable to actually read the database:

    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
}

running the following tests:

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
}

Which I guess is because my main target does not have access to resources in the Test target. So what is the best way to test the code that opens the database?

0 Answers