当前位置:  开发笔记 > 数据库 > 正文

Android SQLite数据库单元测试

如何解决《AndroidSQLite数据库单元测试》经验,为你挑选了2个好方法。

我是Android应用程序开发的新手,我刚做了一个笔记应用程序.我想为数据库的insertNote,readNote和updateNote方法进行单元测试.我该怎么做?这是我的数据库的代码.谢谢.

public class  DatabaseManager extends SQLiteOpenHelper {


public static final String Database_Name = "Notes Database";
public static final String Table_Name = "notes";

public static final String Column_id = "textId";
public static final String Column_title = "textTitle";
public static final String Column_body = "textBody";

public DatabaseManager(Context context){
    super(context, Database_Name, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db){
    db.execSQL("CREATE TABLE " + Table_Name + " (" + Column_id +
            " INTEGER PRIMARY KEY AUTOINCREMENT, " + Column_title +
            " TEXT, " + Column_body + " TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
    db.execSQL("DROP TABLE IF EXISTS" + Table_Name);
    onCreate(db);
}

public void insertNote(Note note){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(Column_title, note.getTextTitle());
    values.put(Column_body, note.getTextBody());

    boolean result = db.insert(Table_Name, null, values) > 0;
    if (result == true)
        Log.d("Create", "Data Has Been Saved");
    db.close();
}

public Cursor readNote(int id){
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.rawQuery("SELECT * FROM " + Table_Name + " WHERE _ROWID_ = " + id, null);

    if (cursor != null){
        cursor.moveToFirst();
    }

    Note myNote = new Note();
    myNote.textId = cursor.getInt(cursor.getColumnIndex(Column_id));
    myNote.textTitle = cursor.getString(cursor.getColumnIndex(Column_title));

    return cursor;
}

public ArrayList getNoteList(){
    ArrayList noteList =  new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + Table_Name, null);
    cursor.moveToFirst();

    if (cursor.moveToFirst()){
        do{
            //noteList.add(cursor.getInt(cursor.getColumnIndex(Column_id)));
            noteList.add(cursor.getString(cursor.getColumnIndex(Column_title)));
        }
        while (cursor.moveToNext());
    }

    return noteList;
}

public int updateNote(Note note){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put("textTitle", note.getTextTitle());
    values.put("textBody", note.getTextBody());

    int update = db.update(Table_Name, values, Column_id + " = ?", new String[]{Integer.toString(note.getTextId())});
    return update;
}

public Integer deleteNote(int id){
    SQLiteDatabase db = this.getWritableDatabase();
   return db.delete(Table_Name, Column_id + " = ?", new String[]{Integer.toString(id)} );
}

public int getCount(){
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + Table_Name, null);
    cursor.close();

    return cursor.getCount();
}

}



1> Cabezas..:

实现SQLite测试的一种方法是使用检测单元测试,使用Android测试包中的InstrumentationRegistry来获取Context.

这是一个关于GitHub的教程和示例的示例:

import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.List;

import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

@RunWith(AndroidJUnit4.class)
@LargeTest
public class SQLiteTest {

    private RateDataSource mDataSource;

    @Before
    public void setUp(){
        mDataSource = new RateDataSource(InstrumentationRegistry.getTargetContext());
        mDataSource.open();
    }

    @After
    public void finish() {
        mDataSource.close();
    }

    @Test
    public void testPreConditions() {
        assertNotNull(mDataSource);
    }

    @Test
    public void testShouldAddExpenseType() throws Exception {
        mDataSource.createRate("AUD", 1.2);
        List rate = mDataSource.getAllRates();

        assertThat(rate.size(), is(1));
        assertTrue(rate.get(0).toString().equals("AUD"));
        assertTrue(rate.get(0).getValue().equals(1.2));
    }

    @Test
    public void testDeleteAll() {
        mDataSource.deleteAll();
        List rate = mDataSource.getAllRates();

        assertThat(rate.size(), is(0));
    }

    @Test
    public void testDeleteOnlyOne() {
        mDataSource.createRate("AUD", 1.2);
        List rate = mDataSource.getAllRates();

        assertThat(rate.size(), is(1));

        mDataSource.deleteRate(rate.get(0));
        rate = mDataSource.getAllRates();

        assertThat(rate.size(), is(0));
    }

    @Test
    public void testAddAndDelete() {
        mDataSource.deleteAll();
        mDataSource.createRate("AUD", 1.2);
        mDataSource.createRate("JPY", 1.993);
        mDataSource.createRate("BGN", 1.66);

        List rate = mDataSource.getAllRates();
        assertThat(rate.size(), is(3));

        mDataSource.deleteRate(rate.get(0));
        mDataSource.deleteRate(rate.get(1));

        rate = mDataSource.getAllRates();
        assertThat(rate.size(), is(1));
    }
}



2> piotrek1543..:

尝试找一些教程,关于Java中单元测试SQLite数据库的文章.Java和Android中的单元测试肯定是一样的.

虽然你会在Stack上找到这些主题:

如何使用junit测试Android sqlite?

如何在android中测试处理SQLite数据库的方法?

或者这篇文章:

带有单元测试的Android Easy SQLite

根据使用Junit测试SQLite数据库,请检查:

SQLiteOpenHelper的Android JUnit测试

你会在哪里找到这个解决方案:

对于一个简单的DatabaseHandler:



    public class MyDatabase extends SQLiteOpenHelper {
      private static final String DATABASE_NAME = "database.db";
      private static final int DATABASE_VERSION = 1;

      public MyDatabase(Context context){
          super(context, DATABASE_NAME, null, DATABASE_VERSION);
      }

      @Override
      public void onCreate(SQLiteDatabase db){
          // some code
      }

      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
          // some code
      }
    }

我创建了一个AndroidTestCase:



  public class DatabaseTest extends AndroidTestCase {
      private MyDatabase db;

        @Override
      public void setUp() throws Exception {
            super.setUp();
          RenamingDelegatingContext context = new RenamingDelegatingContext(getContext(), "test_");
          db = new MyDatabase(context);
      }

        @Override
      public void tearDown() throws Exception {
          db.close(); 
          super.tearDown();
      }

        //According to Zainodis annotation only for legacy and not valid with gradle>1.1:
        //@Test
      public void testAddEntry(){
          // Here i have my new database wich is not connected to the standard database of the App
      }
  }

阅读:

使用Junit测试写入和读取SQLite

使用JUnit测试SQLiteOpenHelper子类

推荐阅读
农大军乐团_697
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有