Skip to content

Instantly share code, notes, and snippets.

@Turnsole
Created October 30, 2020 16:13
Show Gist options
  • Save Turnsole/506feebcb282a4c9c11d1f90591d84af to your computer and use it in GitHub Desktop.
Save Turnsole/506feebcb282a4c9c11d1f90591d84af to your computer and use it in GitHub Desktop.
package com.lastminutedevice.gists;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import com.google.firebase.FirebaseApp;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.util.ReflectionHelpers;
/**
* On a real running app, the FirebaseInitProvider would have initialized FirebaseApp
* on application start. Robolectic doesn't make that happen.
* <p>
* This gets around that problem by having it initialize itself if needed.
*/
@Implements(FirebaseApp.class)
public class ShadowFirebaseApp {
@Implementation
public static FirebaseApp getInstance() {
try {
return Shadow.directlyOn(FirebaseApp.class, "getInstance");
} catch (IllegalStateException exception) {
// It hasn't been initialized.
}
Context targetContext = InstrumentationRegistry
.getInstrumentation()
.getTargetContext();
ReflectionHelpers.ClassParameter<Context> contextClassParameter = ReflectionHelpers
.ClassParameter
.from(Context.class, targetContext);
Shadow.directlyOn(FirebaseApp.class, "initializeApp", contextClassParameter);
return Shadow.directlyOn(FirebaseApp.class, "getInstance");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment