Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

robolectric 2 - create activity under test with intent

I am writing unit test with Robolectric. The setup looks like this

@RunWith(RobolectricTestRunner.class)
public class MiAirlineActivityTest {
    @Before
    public void setUpFor() {
        Intent intent = new Intent(HOW_TO_PASS_CONTEXT_HERE, MiAirlineActivity.class);
        intent.putExtra(EMPLOYEEID_EXTRA, "username");

        miAirlineActivity = Robolectric.buildActivity(MiAirlineActivity.class)
                                .withIntent(intent).start().get();
    }
}

How to pass the context while creating the new intent. I followed the example from this question.

There @David says,

"... i needed to give a Context and the class of the Activity it was being sent to"

How exactly I can do that ?

Note: Please don't mark it as duplicate of the above linked question. I am asking a new question since I could not add comment there.

like image 444
vikas Avatar asked Jul 30 '13 09:07

vikas


People also ask

Is Robolectric deprecated?

setupActivity() is deprecated in Android unit test. Save this question.

How does Robolectric work?

Robolectric works by creating a runtime environment that includes the real Android framework code. This means when your tests or code under test calls into the Android framework you get a more realistic experience as for the most part the same code is executed as would be on a real device.

What is Robolectric test cases?

Robolectric provides a JVM compile version of the android. jar file. Robolectric handles views, resource loading, and many other things that are implemented in the Android native. This enables you to run your Android tests in your development environment, without requiring any other setup to run the test.


1 Answers

miAirlineActivity = Robolectric.buildActivity(MiAirlineActivity.class).create().get();
Intent intent = new Intent();
intent.putExtra(EMPLOYEEID_EXTRA, "username");
miAirlineActivity.setIntent(intent);
miAirlineActivity.onCreate(new Bundle());

This will launch your activity with the desired intent

like image 132
user2483079 Avatar answered Oct 14 '22 22:10

user2483079