user3252344
user3252344

Reputation: 758

Starting a test with ActivityScenarioRule - AndroidStudio

I'm trying to set up some basic instrumented tests which I am running with AndroidStudio on my physical device.

The test is fairly straightforward:

@RunWith(AndroidJUnit4.class)
public class MyActivityTest {
    private ActivityScenarioRule<MyActivity> scenarioRule = new ActivityScenarioRule<>(MyActivity.class);
    
    @Test
    public void onFoo() {
        ActivityScenario scenario = scenarioRule.getScenario();
    }
}

When it runs, this happens:

java.lang.NullPointerException: throw with null exception
at androidx.test.internal.util.Checks.checkNotNull(Checks.java:34)
at androidx.test.ext.junit.rules.ActivityScenarioRule.getScenario(ActivityScenarioRule.java:118)
at com.me.sample.activities.MyActivityTest.onFoo(MyActivityTest.java:...)

According to the documents, NullPointerException is thrown if you use getScenario() when no test is running. I am running these tests with the AndroidStudio UI and the tests are appearing in the test running window, so it doesn't make sense to me that it's throwing that exception.

Do I need to add a before() method to set up the scenarioRule? Is there some setting I'm missing? Or could this be caused by a dependency or something in MyActivity?

Upvotes: 1

Views: 3840

Answers (1)

user3252344
user3252344

Reputation: 758

I was missing annotations. This is the version which works:

@RunWith(AndroidJUnit4.class)
@SmallTest
public class MyActivityTest {
    
    @Rule
    public ActivityScenarioRule<MyActivity> activityRule = new ActivityScenarioRule<>(MyActivity.class);

    @Test
    public void foo() {
        ActivityScenarioRule<MyActivity> scenario = activityRule.getScenario()
    }
}

Upvotes: 3

Related Questions