Reputation: 725
I am trying to run some integration tests with Espresso on a simple activity that once launched triggers a loader to retrieve some data.
The problem is that when I run my tests (even very simple such as checking if a button is on the main page) the result varies continuously, and I keep getting various times NPE
Attempt to invoke virtual method 'android.content.Context.getApplicationContext()' on a null object reference
My activity is empty and holds a fragment, and the error can get tracked back to when, to launch the loader, I ask for the context
MyLoader loader = new MyLoader(getActivity(), certainUrl);
From this I get that getActivity()
returns null
sometimes, and then down the line this throws an exception (since in the Android Loader class the method context.getApplicationContext is called)
This is my test class
public class HomeFragmentTest extends ActivityInstrumentationTestCase2<HomeActivity> {
private HomeActivity _activity;
public HomeFragmentTest() {
super(HomeActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
_activity = getActivity();
injectInstrumentation(getInstrumentation());
}
public void testButton() {
onView(withId(R.id.button))
.check(matches(allOf(
isDisplayed(),
ViewMatchers.isCompletelyDisplayed()
)));
}
}
Thank you all for the help
Upvotes: 2
Views: 1577
Reputation: 19361
Change your setUp
method like in this example:
public class FirstActivityUnitTest extends
android.test.ActivityUnitTestCase<FirstActivity> {
private FirstActivity activity;
public FirstActivityUnitTest() {
super(FirstActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
Intent intent = new Intent(getInstrumentation().getTargetContext(),
FirstActivity.class);
startActivity(intent, null, null);
activity = getActivity();
}
@SmallTest
public void testSomething() {
// assertions here
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
}
Also check if in build.gradle
file you have these dependencies:
android {
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
dependencies {
androidTestCompile 'com.android.support:support-annotations:23.+'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2.1'
}
The most important here is to declare testInstrumentationRunner
Upvotes: 1