2017-05-06 22 views
1

我試圖創建一個greenDAO數據庫會話對象以用於我的junit測試。當我嘗試獲取SQLiteDatabase對象時,我總是得到空值。 沒有錯誤返回,我不明白爲什麼。爲junit測試設置greenDAO會話對象

代碼如下:

@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測試測試,但他們更慢的和不必要的測試平臺無關的邏輯。

+0

是應該是單元測試還是集成測試? –

+0

它應該測試一箇中間層類 – ByteArtisan

+0

你嘲笑的上下文。在傳遞給DevOpneHelper之前,您是否應該先設置它? –

回答

0

找到了解決辦法,並涉及幾個步驟:

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之外使用。