gpt4 book ai didi

java - 尝试测试 SQLiteOpenHelper 但 getWritableDatabase() 抛出 Null

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:43:29 26 4
gpt4 key购买 nike

我正在尝试使用我的 SQLiteOpenHelper 对象在 Android Studio 中针对我的应用程序数据库编写一个 junit 测试。每次它遇到插入方法时,我都会得到一个 NullPointerException。我在使用 getContext() 和我设置的 mockContext 之间来回切换但没有骰子。我已经启动并运行了我的模拟器。有人可以告诉我我做错了什么吗?

public class LocationDatabaseHelperTest extends AndroidTestCase {

private SQLiteDatabase testDB;
private SQLiteDatabase readDB;
private LocationDatabaseHelper dbh;
private RenamingDelegatingContext mockContext;
private ContentValues cv;



/**
*Sets up a mock context to initialize the
* LocationDatabaseHelper object.
* @throws Exception
*/
public void setUp() throws Exception {
super.setUp();


final String prefix = "test";
mockContext = new RenamingDelegatingContext(getContext(),prefix);
dbh = new LocationDatabaseHelper(mockContext);

try {
testDB = dbh.getWritableDatabase();
} catch(Exception ex){
ex.printStackTrace();
}

readDB = dbh.getReadableDatabase();
cv = new ContentValues();
}


/**
*Tests that asserts LocationDatabaseHelper object instantiates.
*/
public void testLocationDatabaseHelper() {
assertNotNull(dbh);
}



public void testInsert() {


String id = "seattle";
float heading = (float) 20.178545;
double longitude = 122.20;
double lat = 47.37;
float speed = (float) 65.4587;
long time = System.currentTimeMillis();
LocationPackage locations = new LocationPackage(id,heading,longitude, lat,speed, time);


cv.put(dbh.COLUMN_LOCATION_id, (String) locations.id);
cv.put(dbh.COLUMN_LOCATION_HEADING, (float) locations.heading);
cv.put(dbh.COLUMN_LOCATION_lat, (double) locations.latitude);
cv.put(dbh.COLUMN_LOCATION_SPEED, (float) locations.speed);
cv.put(dbh.COLUMN_LOCATION_long, (double) locations.longitude);
cv.put(dbh.COLUMN_LOCATION_TIMESTAMP, (long) locations.time);


testDB.insert(dbh.TABLE_LOCATION, null, cv);



String selectQuery = "SELECT * FROM " + dbh.TABLE_LOCATION;
Log.i(dbh.toString(), selectQuery);
Cursor c = readDB.rawQuery(selectQuery, null);
if(c!=null)
c.moveToFirst();

String locID = c.getString(c.getColumnIndex(dbh.COLUMN_LOCATION_id));

//Log.i("LocationID: ", locID);
assertEquals(locID, "userid");


//assertTrue(insertID != -1);
}


public void tearDown() throws Exception {

super.tearDown();

//dbh.clearDatabase();
}

}

最佳答案

您忘记打开数据库。执行 dbh.open()。之后不要忘记关闭您的数据库。

关于java - 尝试测试 SQLiteOpenHelper 但 getWritableDatabase() 抛出 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30553336/

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