Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SQLite Database Unit Testing

I'm new to android app development and I just made a note app. I want to do unit tests for the insertNote, readNote and updateNote methods for the database. How do I go about this? This is the code for my database. Thanks.

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<String> getNoteList(){
    ArrayList<String> 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();
}

}

like image 206
Anderson Avatar asked Dec 14 '15 03:12

Anderson


People also ask

How to unit test SQLite Database in Android?

One way to implement SQLite testing is with an instrumented unit test, using the InstrumentationRegistry in the Android test package to obtain a Context. Show activity on this post. Try to find some tutorials, articles about unit testing SQLite database in Java. Unit Testing in Java and Android is certainly the same.

What is AndroidX test?

AndroidX Test is a collection of Jetpack libraries that lets you run tests against Android apps. It also provides a series of tools to help you write these tests. For example, AndroidX Test provides JUnit4 rules to start activities and interact with them in JUnit4 tests.

How do you do the DAO test?

Enzyme test: Dao is an analytical test which is carried out in the laboratory using the ELISA method to measure the level of the DAO enzyme in the blood and thus to identify whether the migraine is caused by a deficit in DAO. You should fast for a minimum of eight hours prior to the extraction of blood.


1 Answers

One way to implement SQLite testing is with an instrumented unit test, using the InstrumentationRegistry in the Android test package to obtain a Context.

Here is an example from a tutorial and an example on 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> 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> rate = mDataSource.getAllRates();

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

    @Test
    public void testDeleteOnlyOne() {
        mDataSource.createRate("AUD", 1.2);
        List<Rate> 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> 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));
    }
}
like image 180
Cabezas Avatar answered Sep 25 '22 00:09

Cabezas