Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException from LeakCanary when running Robolectric tests

Added LeakCanary (1.3) to my Application:

@Override
public void onCreate() {
    super.onCreate();
    Fabric.with(this, new Crashlytics());
    LeakCanary.install(this);

When I run the Robolectric test suite for my application I get a NullPointerException in LeakCanary.

Caused by: java.lang.NullPointerException
at com.squareup.leakcanary.LeakCanary.isInServiceProcess(LeakCanary.java:165)
at com.squareup.leakcanary.LeakCanary.isInAnalyzerProcess(LeakCanary.java:141)
at com.squareup.leakcanary.LeakCanary.install(LeakCanary.java:52)
at com.squareup.leakcanary.LeakCanary.install(LeakCanary.java:43)
at com.package.application.MyApplication.onCreate(MyApplication.java:50)
at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:131)
at org.robolectric.RobolectricTestRunner.setUpApplicationState(RobolectricTestRunner.java:431)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:224)

I added that Im using Crashlytics to point out that it (and other methods as well) receives the same Application but does not throw any Exceptions.

Wasn't sure if this should be here or on GitHub issues for LeakCanary. Anyone else experiencing this issue?

like image 717
erafn Avatar asked May 11 '15 13:05

erafn


1 Answers

Converting my comment to the answer.

Robolectric provides way to deal with different initialisations and application test lifecycles through test application.

Here is your application class:

public class <YourAppplication> extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Fabric.with(this, new Crashlytics());
        LeakCanary.install(this);
    }
}

You should put in test sources in the same package as yours application next class:

public class Test<YourAppplication> extends <YourApplication> {
    @Override
    public void onCreate() {
    }
}

Robolectric will load it instead of your application. As you can see I suppress all static initialisations from your application.

You can find more details here

like image 170
Eugen Martynov Avatar answered Sep 27 '22 21:09

Eugen Martynov