如何在Android中使用SQLite在Robolectric单元测试中获取上下文

问题描述

我想使用Robolelectric在Android中为SQLiteOpenHelper做一些单元测试。但是,由于无法获取上下文,因此无法创建数据库。我尝试了How can we access context of an application in Robolectric?此处提到的4个选项,但没有一个起作用。在这里,您可以看到测试类的代码,并且在“ setUp”方法中,可以看到//

之后我尝试使用相应错误消息的不同选项
package com.example.td.barapp;

import android.content.Context;
import android.database.Cursor;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;


@RunWith(RobolectricTestRunner.class)


public class DataBaseHelperTest {

    private DataBaseHelper helperDB;


    @Before
    public void setUp() throws Exception {
        // Context context = ShadowApplication.getInstance().applicationContext; //Error: Cannot resolve symbol 'applicationContext'
        //Context context = Robolectric.application; // Error: Cannot resolve symbol application
        //Context context = ApplicationProvider.getApplicationContext(); // Error: Cannot resolve symbol 'ApplicationProvider'
        //Context context = RuntimeEnvironment.systemContext; // Error: Cannot resolve symbol 'systemContext'
//Context context = getClass().getClassLoader(); // Error: Required type: Context Provided: ClassLoader
        Context context = InstrumentationRegistry.getInstrumentation().getContext(); // Error: Cannot resolve symbol 'InstrumentationRegistry'
        helperDB = new DataBaseHelper(context);
    }

    @After
    public void tearDown() {
        helperDB.close();
    }

    @Test
    public void insertDataDB_TableRatings() {
        boolean insertRating = helperDB.insertDataDB_TableRatings("Orange Juice","Any",1,0 );

        Assert.assertTrue(insertRating);
    }

    @Test
    public void getDataDB_TableRating() {
        String drinkName = "Orange Juice";
        String drinkStrength = "Any";
        String drinkSize = "Any";

        boolean insertRating = helperDB.insertDataDB_TableRatings(drinkName,drinkStrength,drinkSize,0 );


        Cursor res = helperDB.getDataDB_TableRating(drinkName,drinkSize);
        Assert.assertFalse(res.getCount()==0);

        res.moveToFirst();
        Assert.assertEquals (res.getString(0),drinkName);
        Assert.assertEquals (res.getString(6),"1");

        drinkSize = "Large";

        boolean insertRating2 = helperDB.insertDataDB_TableRatings(drinkName,0 );

        res = helperDB.getDataDB_TableRating(drinkName,drinkSize);
        Assert.assertFalse(res.getCount()==0);

        res.moveToFirst();
        Assert.assertEquals (res.getString(2),drinkName);
        Assert.assertEquals (res.getString(7),"1");


    }

    @Test
    public void updateDataDB_TableRatings() {
        String drinkName = "Orange Juice";
        String drinkStrength = "Any";
        String drinkSize = "Any";

        boolean insertRating = helperDB.insertDataDB_TableRatings(drinkName,0 );
        boolean valueUpdated = helperDB.updateDataDB_TableRatings(drinkName,2,0);

        Cursor res = helperDB.getDataDB_TableRating(drinkName,drinkSize);
        Assert.assertFalse(res.getCount()==0);
        res.moveToFirst();
        Assert.assertEquals (res.getString(8),"1");
    }

    @Test
    public void deleteDataDB_TableRatings() {
        String drinkName = "Orange Juice";
        String drinkStrength = "Any";
        String drinkSize = "Large";

        boolean insertRating = helperDB.insertDataDB_TableRatings(drinkName,0 );
        helperDB.deleteDataDB_TableRatings (drinkName,drinkSize);
    }
}

我还在build.gradle文件中添加了以下几行:

testImplementation 'junit:junit:4.13'
testImplementation 'org.robolectric:robolectric:3.0'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

您介意告诉我我犯了什么错误吗?我会很感激每个评论。

更新:似乎我可能缺少一些依赖项,因此我将build.gradle文件与依赖项一起上载。您介意告诉我错误是什么,为什么我无法从Roblectric获得任何背景信息?

apply plugin: 'com.android.application'
apply plugin: "androidx.navigation.safeargs"


android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.td.barapp"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        viewBinding {
            enabled = true
        }
        dataBinding {
            enabled=true
        }

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'
        }
    }
}

dependencies {
    def nav_version = "2.3.0"
    implementation fileTree(dir: 'libs',include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.2.0-alpha06'
    testImplementation 'junit:junit:4.13'
    testImplementation 'org.robolectric:robolectric:3.0'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    androidTestImplementation 'android.arch.core:core-testing:1.2.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation "androidx.recyclerview:recyclerview:1.1.0"
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation "androidx.navigation:navigation-fragment:$nav_version"
    implementation "androidx.navigation:navigation-ui:$nav_version"


}

解决方法

我非常确定您不能使用robolectric测试SQLite。例如,我的房间测试只能在AndroidTest / Instrumented中运行。如果您愿意改用Room而不是直接使用SQLite,则它的测试已记录在案。

如果您想了解有关房间的更多信息,请访问this code lab

如果您想了解有关其测试的更多信息,可以对其进行检查here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...