6

I'm trying to mock an instance of Firebase Analytics for Android unit testing, but my Firebase variable remains undefined after I call Firebase's getInstance() method - which should initialize an instance of the FirebaseAnalytics class.

I'm using PowerMock and Android Studio. Here's my Test.java file (no tests yet - just trying to initialize a mock of the class):

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 18, manifest = 
Config.NONE)
@PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" })
@PrepareForTest({FirebaseAnalytics.class})
public class FirebaseTest {
    @Rule public PowerMockRule rule = new PowerMockRule();
    @Mock Application application;
    @Mock Analytics analytics;
    FirebaseAnalytics firebase;

    @Before
    public void setUp() {
        initMocks(this);

        /* mock context */
        when(analytics.getApplication()).thenReturn(application);

        PowerMockito.mockStatic(FirebaseAnalytics.class);

when(FirebaseAnalytics.getInstance(application)).thenReturn(firebase);  /* firebase remains null */
        PowerMockito.mockStatic(FirebaseAnalytics.class);
    }

FirebaseAnalytics is a final class, and getInstance() is a static final method. I'm not sure whether these may make mocking difficult. Any ideas are appreciated!

Brennan
  • 169
  • 8
  • I don't see you initializing your `FirebaseAnalytics` class to anything. When you do `.thenReturn(firebase)` the `firebase` object your putting in there may still be null. – Rafa Aug 30 '17 at 15:55
  • Could you say more about what you're trying to accomplish and exactly what problem you're running into? I can't really tell. What is your class that you're trying to test here? – Doug Stevenson Aug 31 '17 at 04:15

0 Answers0