Robolectric 使用 Firebase 进行应用测试

Robolectric app testing with Firebase

我正在尝试为我的演示者编写一个简单的 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 一起使用吗?

如果您不在代码中使用它们进行测试,则可以通过构造函数注入它们:

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

然后你为他们注入 null,记住这是使用 null 的一种非常糟糕的方式。 更好的方法是使用像 Mockito 这样的库或使用 interfaces/wrapper 等

例如使用接口

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());