Android SQLite Database Unit Testing

后端 未结 3 533
感情败类
感情败类 2020-12-31 07:30

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 abo

3条回答
  •  不思量自难忘°
    2020-12-31 08:03

    Try to find some tutorials, articles about unit testing SQLite database in Java. Unit Testing in Java and Android is certainly the same.

    Although you would find these topics on Stack:

    How to test Android sqlite with junit?

    How to test methods that deal with SQLite database in android?

    or this article:

    Android Easy SQLite With Unit Tests

    According to testing SQLite databese with Junit, check this:

    Android JUnit test for SQLiteOpenHelper

    where you would find this solution:

    For a simple 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
          }
        }
    

    I created an 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
          }
      }
    

    Read also:

    Using Junit to test writing and reading to SQLite

    Testing SQLiteOpenHelper subclass with JUnit

提交回复
热议问题