1

I am trying to create a greenDAO database session object for use in my junit tests. When i try to get the SQLiteDatabase object i always get null. No error is returned and i can't figure out why.

Below the code:

@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();

    }
}

Note: i know i can test it using android tests, but they are much more slow and unnecessary to test independent platform logic.

MiguelSlv
  • 14,067
  • 15
  • 102
  • 169

1 Answers1

0

Found the solution and involves several steps:

1) use Robolectric package to be able to create an Application

At app.gradle add:

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

2) Build your test class like this:

@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) Finally define working directory as posted here for your tests so Robolectric can find the project manifest file.

I am not sure if will work consistently on other tests at this time, and maybe would be preferable to use android tests instead. GreenDao doesn't seems tailored to be used outside the android.

MiguelSlv
  • 14,067
  • 15
  • 102
  • 169