vinothp
vinothp

Reputation: 10069

Activity Unit testing using ActivityUnitTestCase

I am trying to write Unit tests for activity methods using ActivityUnitTestCase. But always i am getting null pointer exception while calling startActivity(). Below is my code.

I debugged and found this always returning null getInstrumentation().getTargetContext(). But i don't really understand whats happening here.

CODE

public class ScoreBoardActivityTest extends ActivityUnitTestCase<ScoreBoardActivity> {

public ScoreBoardActivity activity;


public ScoreBoardActivityTest() {
    super(ScoreBoardActivity.class);
}

@Override
protected void setUp() throws Exception {
    super.setUp();
    startActivity(new Intent(getInstrumentation().getTargetContext(), ScoreBoardActivity.class), null, null);
    activity = getActivity();
}

@Test
public void testActivityNotNull(){
    Assert.assertNull(activity);
}

@Test
public void testBatsmanOneAddRunButtonClickUpdateTotalRuns(){
    activity.onBatsmanOneAddRunClick(null);
    Assert.assertEquals(activity.totalRuns, 1);
}
}

What i am doing wrong here?

Is there anything else i need to set it up?

Upvotes: 1

Views: 393

Answers (1)

CmosBattery
CmosBattery

Reputation: 954

I made a note for this before for ActivityUnitTestCase:

// This will always be null with extends ActivityUnitTestCase<>
// home = getActivity();

You can get [to] the context by doing this:

public class ScoreBoardActivityTest extends ActivityInstrumentationTestCase2<ScoreBoardActivity> {

    private ScoreBoardActivity scoreBoardActivity;

    public ScoreBoardActivityTest() {
        super(ScoreBoardActivity.class);
    }

    // Called before every test case method
    @Override
    protected void setUp() throws Exception {
        super.setUp();

        // Use here to start the activity anew before each test
        // Use in test methods should re-start the activity each time called or bring it back after
        // finishing or intents
        scoreBoardActivity = getActivity();
    }

Another note is that ActivityUnitTestCase is for VERY basic testing. Its nearly useless imo and not something I care about using.

The ActivityInstrumentationTestCase2 is what allows use of the activity and is started with getActivity() if I remember correctly.

If you want to specifically see context it then might look like:

scoreBoardActivity.getApplicationContext()

But you can just use scoreBoardActivity.

Also note that tests are alphabetical so your testActivityNotNull() could get behind other tests such as testAcorn or testAbat.

Upvotes: 0

Related Questions