我刚开始学习JUnit测试。
请问有人可以帮我,教我如何测试我的SQLiteOpenHelper
类。
也就是说,我需要实现哪些类以及如何测试我的数据库和表格。 我正在使用Eclipse IDE。
从API 24开始,RenamingDelegatingContext
已经被弃用。 另一个线程建议使用Robolectric的RuntimeEnvironment.application
,如这篇Medium文章所述。
对于一个简单的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 which is not connected to the standard database of the App
}
}
RenamingDelegatingContext()
的做法,我给予+1的支持,它在测试中非常有用。 - eternay您也可以使用JUnit4风格编写Android数据库测试。您只需要在数据库中添加以下依赖项即可:
http://www.singhajit.com/testing-android-database/androidTestCompile('com.android.support.test:runner:0.3'){
exclude group: 'com.android.support', module: 'support-annotations'
}
并将您的测试类标记如下:
@RunWith(AndroidJUnit4.class)
public class DatabaseTest {
@Test
public void myFirstTest(){
//your test
}
}
RenamingDelegatingContext在v24中已经弃用。使用Robolectric进行测试。以下是一个示例(使用Kotlin):
@RunWith(RobolectricGradleTestRunner::class)
@Config(constants = BuildConfig::class, sdk = intArrayOf(LOLLIPOP), packageName = "com.elyeproj.simpledb")
class ExampleUnitTest {
lateinit var dbHelper: DbHelper // This is your SQLOpenHelper class
@Before
fun setup() {
dbHelper = DbHelper(RuntimeEnvironment.application) // Your new context from Robolectric
dbHelper.clearDbAndRecreate() // A function just to clear and recreate DB
}
@Test
@Throws(Exception::class)
fun testDbInsertion() {
// Given
val testStr1 = "testing"
val testStr2 = "testing"
// When
dbHelper.insertText(testStr1)
dbHelper.insertText(testStr2)
// Then
assertEquals(dbHelper.getAllText(), "$testStr1-$testStr2-")
}
@After
fun tearDown() {
dbHelper.clearDb() // A function just to clear the DB
}
}
这个问题非常抽象。
我建议您阅读《Android测试指南》。它有一些简单的测试Android应用程序的示例。
不知道您的代码,我猜测您的SQLiteOpenHelper是由一个Activity或Service使用的。我认为这些Activities/Services是您必须测试的。
对于Activity,一个很好的起点应该是ActivityInstrumentationTestCase2,对于Service则是ServiceTestCase。
希望能帮到您。