我正在尝试为演示者编写一个简单的 Robolectric 测试,它使用 Firebase 数据库和 Firebase Auth。但每次我尝试开始测试时,它都会抛出 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)
我的测试很简单
@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);
}
}
在我的 Presenter 构造函数中,我只获取了 Firebase 实例。
public LoginPresenter() {
this.firebaseAuth = FirebaseAuth.getInstance();
this.database = FirebaseDatabase.getInstance().getReference();
}
有什么方法可以将 Robolectric 与 Firebase 结合使用吗?
最佳答案
如果您不在代码中使用它们来测试,则可以通过构造函数注入(inject)它们:
public LoginPresenter(FireBaseAuth firebaseAuth, FirebaseDatabase database){
this.firebaseAuth = firebaseAuth;
this.database = database;
}
然后您为它们注入(inject) null
,请记住,使用 null
是一种非常糟糕的方法。
更好的方法是使用像 Mockito 这样的库或使用接口(interface)/包装器等。
例如使用接口(interface)
public interface IDatabase {
public List<String> getData();
}
LoginPresenter
:
public LoginPresenter(FireBaseAuth firebaseAuth, IDatabase database){
this.firebaseAuth = firebaseAuth;
this.database = database;
}
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 ...;
}
}
现在使用 IDatabase
模拟数据库非常容易:
public class DatabaseMock implements IDatabase {
public List<String> getData() {
// Return the expected data from the mock
return ...;
}
}
像这样从测试中调用它:
presenter = new LoginPresenter(FirebaseAuth.getInstance(), new DatabaseMock());
关于android - 使用 Firebase 进行 Robolectric 应用程序测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38329812/