Robolectric: BroadcastReceivers created before Application.onCreate

Created on 14 Dec 2018  路  1Comment  路  Source: robolectric/robolectric

Description

Initialization of BroadcastReceivers declared in the Android Manifest occurs before Application.onCreate is called. This is backwards from standard initialization order, and causes issues when initialization occurs in Application.onCreate that creates a dependency that is utilized in a BroadcastReceiver's constructor. In our application, this was related to dependency graph creation. For example:

Application

````java
public class MyApplication extends Application {

private static MyApplication sApplication;

private DependencyGraph mDependencyGraph;

public static MyApplication getApplication() {
    return sApplication;
}

public MyApplication() {
    sApplication = this;
}

public DependencyGraph getDependencyGraph() {
    return mDependencyGraph;
}

public void onCreate() {
    super.onCreate();
    mDependencyGraph = new DependencyGraph();
}

}
````

BroadcastReceiver

````java
public class MyBroadcastReceiver {

@Inject
public MyDependency;

public MyBroadcastReceiver() {
    //When running the test in androidTest suite, without Robolectric, this works. 
    //When using robolectric in the test/ directory, it fails with a NullPointerException, because 
    //Application.onCreate was never called.
    MyApplication.getApplication().getDependencyGraph().inject(this);
}

}
````

Steps to Reproduce

Write a test for the BroadcastReceiver. It will fail upon initialization.

Robolectric & Android Version

Robolectric 4.1
Android compile SDK 26
Build Tools 28.0.3

Link to a public git repo demonstrating the problem:

N/A

>All comments

Any update on this?

Was this page helpful?
0 / 5 - 0 ratings