java - 使用 JUnit 测试 SQLiteOpenHelper 子类

标签 java android testing junit instrumentation

我正在为我的 Android 应用编写 JUnit 测试。我已经通读了 Android 开发人员资源(测试基础知识、Spinner 示例测试等)。现在我想独立于使用它的 Activity 来测试我的 SQLiteOpenHelper 子类。我的想法是扩展ActivityInstrumentationTestCase2<Activity> .可以简单地使用 Activity 吗?作为通用参数还是我需要一个子类?另外,我的方向是否正确,或者是否有更好的方法来测试我的 SQLiteOpenHelper 子类?

最佳答案

我一直在寻找这个问题的答案,并在这里找到了这个链接以及另一个有趣的相关问题:

accepted answer by @Pietro显示一些简单的代码,使用基本的 AndroidTestCase,这将有助于直接回答问题。

public class DatabaseTest extends AndroidTestCase {
    private MyDatabase db;

    public void setUp(){
        RenamingDelegatingContext context 
        = new RenamingDelegatingContext(getContext(), "test_");
        db = new MyDatabase(context);
    }

    public void testAddEntry(){
        // Here I have my new database which is not connected to the standard database of the App
    }

    public void tearDown() throws Exception{
        db.close(); 
        super.tearDown();
    }
}

我很高兴它看起来如此简单。就我而言,我是 Android 测试的新手,所以目前即使是简单的东西看起来也很困难。


但是有趣的部分是关键,是使用RenamingDelegatingContext类作为您的“上下文”,而不仅仅是使用普通上下文。这似乎建立在@Jens 的评论之上。

此类包装给定的上下文并将大多数操作委托(delegate)给该上下文。有用的部分是它使用重命名的数据库/文件名执行数据库和文件操作 ( see documentation online )。

这允许您的 TEST 代码使用与您的 PRODUCTION 代码不同的实际数据库实例 - 至少在我的情况下这是有用的。


这是另一篇相关的帖子,其中接受的答案说的几乎是同一件事:

其中有一些关于使用 ContentProvider 的有用提示(但那是另一天的不同问题)。

关于java - 使用 JUnit 测试 SQLiteOpenHelper 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12991477/

相关文章:

java - ejb远程方法在本地工作但在远程给出错误

java - 使用 google Drive api 让 children 没有垃圾

java - 为什么 "Release Connection"在 jdbcTemplate#execute 的 catch{} block 和 finally{} block 中执行

java - 如何在 android 中的图像上创建自定义可点击形状?

android - 将消息从 android 发布到 AWS SNS 主题

testing - Jenkins 上的 TestNG 结果组

Class 的 Java 泛型问题

安卓数据绑定(bind) : Wrong BR class generated for obfuscated AAR

json - 如何使用 scala 中的 json4s 库测试我为解析器创建的案例类是否正确?

c# - 通过 Controller 使用 ExecuteAsync 测试 IHttpActionResult