Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 views
in Technique[技术] by (71.8m points)

sqlite - Android JUnit test for SQLiteOpenHelper

I am new to junit testing.

Can anyone help me , how to test my SQLiteOpenHelper class.

Means what classes I have to implement and how to test my db and tables. I am using Eclipse IDE.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As of API Level 24, RenamingDelegatingContext is deprecated. Another thread suggests to use Robolectric's RuntimeEnvironment.application as described in this Medium article.

The old answer for reference:

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 which is not connected to the standard database of the App
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...