我在访问上下文时遇到问题,因此可以创建一个测试数据库。对于如何对SQLite数据库进行单元测试,我找不到任何有效的解决方案。这可能就是为什么我在
上收到NullPointerException的原因db.addUser(user);
任何建议将不胜感激。到目前为止,这是我的代码:
数据库类:
public class Database extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "UserDB";
private static final String TABLE_USERS = "users";
private static final String KEY_ID = "id";
private static final String KEY_USERNAME = "username";
private static final String KEY_PASSWORD = "password";
private static final String KEY_EMAIL = "email";
private static final String[] COLUMNS = {KEY_ID, KEY_USERNAME, KEY_PASSWORD, KEY_EMAIL};
public Database(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_USER_TABLE = "CREATE TABLE users ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"username TEXT, "+
"password TEXT, "+
"email TEXT )";
db.execSQL(CREATE_USER_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS users");
this.onCreate(db);
}
public void addUser(User user){
Log.d("addUser", user.toString());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USERNAME, user.getUsername());
values.put(KEY_PASSWORD, user.getPassword());
values.put(KEY_EMAIL, user.getEmail());
db.insert(TABLE_USERS, // table
null, values);
db.close();
}
public boolean checkLogin(String username, String password) {
String query = "SELECT * FROM users WHERE username = '"+ username + "' AND password = '" + password+"'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if(cursor.getCount() <= 0) {
cursor.close();
db.close();
return false;
} else {
cursor.close();
db.close();
return true;
}
}
}
LoginTest类:
public class LoginTest {
Database db;
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testSearchDatabase() {
Database db = new Database(this);
String testUser = "testUser";
String testPass = "testPass";
User user = new User(testUser, testPass,"testEmail@gmail.com");
db.addUser(user);
assertTrue(db.checkLogin(testUser, testPass));
}
}
答案 0 :(得分:0)
可以使用以下内容检索上下文:iterating Lorem
iterating ipsum
iterating dolor
iterating sit
iterating amet,
iterating consectetur
iterating adipisci
iterating elit,
iterating ...
RuntimeEnvironment.application