Reputation: 523
I am trying to use Firebase as the backend for my app. If I use the following quickstart guide within my app everything works.
If I check on my firebase data page, data is successfully written.
However if I try to do the same thing inside of an androidTest (instrumentation test) nothing happens - no data is written to the firebase database. I have specified Internet permission in my androidTest manifest, so wondering if there is something else that I need to do to be able to write to firebase from within my tests?
On a related note, once I can do this within instrumentaiton tests, is there a way I can do the same in unit tests?
Many thanks,
Riz
Edit: here is the test I'm trying to run:
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.");
}
}
Upvotes: 3
Views: 2428
Reputation: 1794
In your main application you can define an androidApplication
class to initialize your Firebase Context. Then create an ApplicationTest that extends the ApplicationTestCase :
In Main source :
public class MyApplication extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
Firebase.setAndroidContext(this); //initializeFireBase(context);
isInitialized = true;
}
}
In your Android Test :
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.");
}
}
Upvotes: 1