Android 如何模拟SQLiteDatabase实例?
在我要测试的类中,构造函数中有以下代码Android 如何模拟SQLiteDatabase实例?,android,mockito,android-testing,Android,Mockito,Android Testing,在我要测试的类中,构造函数中有以下代码 public MyClass (Context context){ String db = context.getDatabasePath("mydb.db").getPath(); this.connection = SQLiteDatabase.openOrCreateDatabase(db, null); } mydb.db位于src/test/resources中 这是我的测试课 @RunWith(MockitoJUnitRunn
public MyClass (Context context){
String db = context.getDatabasePath("mydb.db").getPath();
this.connection = SQLiteDatabase.openOrCreateDatabase(db, null);
}
mydb.db位于src/test/resources中
这是我的测试课
@RunWith(MockitoJUnitRunner.class)
public class MyTest {
MyClass myClass;
@Mock
Context context;
@Mock
SQLiteDatabase sqLiteDatabase;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
URL resource =this.getClass().getClassLoader().getResource("mydb.db");
File file = new File(resource.getPath());
doReturn(file).when(context).getDatabasePath("mydb.db");
myClass=new MyClass(context);
}
}
运行测试时,我遇到了异常:
java.lang.RuntimeException: Method openOrCreateDatabase in android.database.sqlite.SQLiteDatabase not mocked. See http://g.co/androidstudio/not-mocked for details.
我已经在我的版本中添加了这个
testOptions {
unitTests.returnDefaultValues = true
}
现在例外情况消失了
但是MyClass的连接是空的
是否可以仅使用Mockito来测试此功能?我已经在其他测试中使用了资源,并且可以正常工作。我已经在其他测试中使用了资源,并且可以正常工作