Testing Robolectric with Firebase

I am trying to write a simple Robolectric test for my lead, which uses the Firebase and Firebase Auth database. But every time I try to run a test, it throws an IllegalStateException.

java.lang.IllegalStateException: FirebaseApp with name [DEFAULT] doesn't exist. at com.google.firebase.FirebaseApp.getInstance(Unknown Source) at com.google.firebase.FirebaseApp.getInstance(Unknown Source) at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source) 

My test is pretty simple

 @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class) public class LoginPresenterTest { private LoginPresenter presenter; private LoginMvpView view; @Before public void beforeEachTest() { presenter = new LoginPresenter(); view = new LoginFragment(); } @Test public void attachView_shouldAttachViewToThePresenter() { presenter.attachView(view); assertSame(presenter.getMvpView(), view); } } 

In my presenter constructor, I just get instances of Firebase.

 public LoginPresenter() { this.firebaseAuth = FirebaseAuth.getInstance(); this.database = FirebaseDatabase.getInstance().getReference(); } 

Can I use Robolectric with Firebase?

+5
source share
1 answer

If you do not use them in your code for testing, you can add them using the constructor:

 public LoginPresenter(FireBaseAuth firebaseAuth, FirebaseDatabase database){ this.firebaseAuth = firebaseAuth; this.database = database; } 

and you enter null for them, remember that this is very bad using null . It is best to use a library like Mockito or use interfaces / wrapper etc.

eg. use interface

 public interface IDatabase { public List<String> getData(); } 

LoginPresenter :

 public LoginPresenter(FireBaseAuth firebaseAuth, IDatabase database){ this.firebaseAuth = firebaseAuth; this.database = database; } 

Normal implementation of IDatabase :

 public class MyDatabase implements IDatabase { private FirebaseDatabase database; public MyDatabase(FirebaseDatabase database) { this.database = database; } public List<String> getDate() { // Use the FirebaseDatabase for returning the getData return ...; } } 

And now it’s very easy to mock a database using IDatabase :

 public class DatabaseMock implements IDatabase { public List<String> getData() { // Return the expected data from the mock return ...; } } 

Call it from the test, for example:

  presenter = new LoginPresenter(FirebaseAuth.getInstance(), new DatabaseMock()); 
+4
source

All Articles