lundi 4 avril 2016

NPE when running InstumentationTests

I have the following InstrumentationTestCase:

@RunWith(AndroidJUnit4.class)
public class TestLogin extends InstrumentationTestCase {

    @Rule
    public ActivityTestRule<WelcomeActivity> mWelcomeActivityRule = new ActivityTestRule<>(WelcomeActivity.class);

    @Rule
    public ActivityTestRule<MainActivity> mMainActivityRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void testLogin() {
        onView(withId(R.id.login_username)).perform(click()).perform(typeText("admin"));
        onView(withId(R.id.login_password)).perform(click()).perform(typeText("pass"), closeSoftKeyboard());
        onView(withId(R.id.login_username)).check(matches(withText("admin")));
        onView(withId(R.id.login_password)).check(matches(withText("pass")));

        onView(withId(R.id.login_button)).perform(click());
    }

    @Test
    public void testVerifyCredentials() {
        SharedPreferences prefs = getInstrumentation().getTargetContext().getSharedPreferences("current.user", Context.MODE_PRIVATE);
        assertTrue(prefs.getBoolean("IsLoggedIn", false));
    }
}

The login flow starts at the WelcomeActivity, then logs in and then we're at the MainActivity. Once we're in the MainActivity, I want to query the SharedPreferences values.

However, I'll get a NullPointerException inside of the following method in MainActivity:

public View insertImage(LinearLayout layout, String id, String url) {
        layout.setGravity(Gravity.CENTER);

        final ImageView imageView = new ImageView(getApplicationContext());
        imageView.setTag(id); //store the movieId per ImageView
        setupOnImageClick(imageView); //setup what to do when we click on one of the posters
        imageView.setPadding(8, 8, 8, 8);

        Picasso.with(this).load(url).resize(900, 800).centerInside().into(imageView, new Callback() {
            @Override
            public void onSuccess() {
                //NPE FOUND HERE, 
                progressMajorPosters.setVisibility(View.GONE);
                progressRatingsPosters.setVisibility(View.GONE);
            }

            @Override
            public void onError() {

            }
        });
        layout.addView(imageView);
        return layout;
    }

Specifically, the error is Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference. This entire method works fine when I'm running the app normally--it only occurs when running this test.

Not sure how to fix it since I know it's valid.

Aucun commentaire:

Enregistrer un commentaire