【问题标题】:Setting up greenDAO session object for a junit test为 junit 测试设置 greenDAO 会话对象
【发布时间】:2017-05-06 13:41:23
【问题描述】:

我正在尝试创建一个greenDAO 数据库会话对象以用于我的junit 测试。当我尝试获取SQLiteDatabase 对象时,我总是得到空值。 没有返回错误,我不知道为什么。

代码下方:

@RunWith(MockitoJUnitRunner.class)
public class ChatRoomModuleTest {

    SomeEntityDao someEntityDao;

    @Mock
    Context mMockContext;

    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule();

    @Before
    public void Before(){

        DaoMaster.DevOpenHelper openHelper = new  DaoMaster.DevOpenHelper(mMockContext, "myapp-db", null);
        SQLiteDatabase db = openHelper.getWritableDatabase(); //always return null;
        DaoSession daoSession = new DaoMaster(db).newSession();
        someEntityDao = daoSession.getSomeEntityDao();

    }
}

注意:我知道我可以使用 android 测试对其进行测试,但是它们要慢得多,并且不需要测试独立的平台逻辑。

【问题讨论】:

  • 应该是单元测试还是集成测试?
  • 应该是测试一个中间层类
  • 你模拟了上下文。你不应该在传递给 DevOpneHelper 之前先设置它吗?
  • 我想到了,但是如何正确设置呢?不知道助手期望什么。
  • 我可以帮助正确设置 junit / mockito,但该课程的期望超出了我的知识范围。

标签: android junit greendao


【解决方案1】:

找到解决方案并涉及几个步骤:

1) 使用 Robolectric 包来创建应用程序

在 app.gradle 添加:

//if your project use multidex
testCompile "org.robolectric:shadows-multidex:3.0"
//otherwise use
//testCompile 'org.robolectric:robolectric:3.1'

2) 像这样构建您的测试类:

@RunWith(RobolectricGradleTestRunner.class) //run test with roboteletric
@Config(constants = BuildConfig.class, sdk = 19)
public class test {

    MyEntityDao myEntityDao;
    DaoSession daoSession;

    @Before
    public void setUp() {

//use roboteletric to create a valid Application Object
        DaoMaster.DevOpenHelper openHelper = new DaoMaster.DevOpenHelper(RuntimeEnvironment.application, null, null);
        SQLiteDatabase db = openHelper.getWritableDatabase();
        Assert.assertNotNull(db);
        daoSession = new DaoMaster(db).newSession();
        myEntityDao = daoSession.getMyEntityDao();
    }


    @Test
    public void t1() {
        MyEntity myEntity = new MyEntity();
        myEntityDao.insert(MyEntity);
    }
}

3) 最后为您的测试定义发布的工作目录here,以便 Robolectric 可以找到项目清单文件。

我不确定此时是否会在其他测试中始终如一地工作,也许改用 android 测试会更好。 GreenDao 似乎并不适合在 android 之外使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-26
    • 2014-04-22
    • 1970-01-01
    • 2023-03-02
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多