2016-03-15 143 views
2

我試圖使用Firebase作爲我的應用程序的後端。如果我在我的應用程序中使用以下quickstart guide一切正常。如何編寫Firebase Android儀器測試?

如果我檢查我的firebase數據頁面,數據被成功寫入。

但是,如果我嘗試在androidTest(檢測測試)中做同樣的事情,則不會發生任何事情 - 沒有數據寫入Firebase數據庫。我在我的androidTest清單中指定了Internet權限,所以想知道是否還有其他需要做的事情可以從我的測試中寫入Firebase?

在一個相關說明中,一旦我可以在instrumentaiton測試中做到這一點,有沒有辦法在單元測試中做同樣的事情?

非常感謝,

里茲

編輯:這裏是我試圖運行測試:

public class FirebaseTest extends InstrumentationTestCase{ 
    private static final String FIREBASE = "https://my-app-name.firebaseio.com/"; 

    @Override 
    @Before 
    public void setUp() { 
     injectInstrumentation(InstrumentationRegistry.getInstrumentation()); 
     Firebase.setAndroidContext(getInstrumentation().getTargetContext()); 
    } 

    @Test 
    public void testWrite(){ 
     Firebase cloud = new Firebase(FIREBASE); 
     cloud.child("message").setValue("Do you have data? You'll love Firebase."); 
    } 
} 
+0

我有同樣的問題,但爲了清楚起見,你可以編輯你的問題來包含一個測試的例子? –

+0

我編輯了這個問題以包含我試圖運行的測試。 – chdryra

+0

你的類應該擴展應用程序或活動來實現這個工作,或者你可以做的就是創建一個應用程序類,並在那裏初始設置爲'Firebase.setAndroidContext(this);'然後進一步完成你的工作 – 1shubhamjoshi1

回答

0

在主應用程序,你可以定義一個androidApplication類初始化火力地堡語境。然後創建一個擴展ApplicationTestCase的ApplicationTest:

在主要來源:

public class MyApplication extends android.app.Application { 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     Firebase.setAndroidContext(this); //initializeFireBase(context); 
     isInitialized = true; 
    } 
} 

在你的Android測試:

public class ApplicationTest extends ApplicationTestCase<MyApplication> { 

    private static MyApplication application; 

    public ApplicationTest() { 
     super(MyApplication.class); 
    } 

    @Override 
    public void setUp() throws Exception { 
     super.setUp(); 
     if (application == null) { 
      application = getApplication(); 
     } 
     if (application == null) { 
     application = (MyApplication) getContext().getApplicationContext(); 
     assertNotNull(application); 
     long start = System.currentTimeMillis(); 
     while (!application.isInitialized()){ 
      Thread.sleep(300); //wait until FireBase is totally initialized 
      if ((System.currentTimeMillis() - start) >= 1000) 
       throw new TimeoutException(this.getClass().getName() +"Setup timeOut"); 
     } 
     } 
    } 


    @Test 
    public void testWrite(){ 
     Firebase cloud = new Firebase(FIREBASE); 
     cloud.child("message").setValue("Do you have data? You'll love Firebase."); 
    } 

} 
+0

謝謝,我試過這個,但是不起作用。測試無法啓動,因爲它無法通過createApplication()創建MyApplication(順便說一句,我認爲應該有一個super.setup(); createApplication();在每個測試之前運行的setUp方法)。它在Instrumentation.newApplication(mApplicationClass,getContext())上失敗;在ApplicationTestCase.java ... – chdryra

+0

中,爲了避免在「onCreate()」方法中傳遞多次,我在靜態模式下做了一個醜陋的setUp,其中存儲了「MyApplication」。我將編輯我的答案以顯示 – toofoo

+0

感謝您的回覆。不幸的是,試圖運行上面的代碼,我得到了一個異常:application =(MyApplication)getContext()。getApplicationContext();.這是我認爲JUnitRunner中的某處出現NullPointerException(在ReflectiveCallable.java中)。 – chdryra