Robolectric (android): Testing events?

I wrote some tests using robolectric, and now I want to make some real test classes.

One of them noticed that I cannot test events like onCreate, onLocationChanged, etc.

What is the standard practice of testing events ...

Should I extract the code inside the events and put them in the method, the event will call the method, and also robolectro can call the method, of course, the method must be public, right?

Also, if I want to check something inside my method, which is usually a private variable, then I will need to add a public getter, right? so can i check this on robolectric?

Is there a better way to output data to robolectric?

Thanks in advance.

+8
android robolectric
source share
2 answers

When testing onCreate, I get robolectric to call onCreate, and then check that the action is in the correct state after onCreate. Here is an example:

@RunWith(RoboTestRunner.class) public class DashboardActivityTest { private DashboardActivity activity; @Before public void setUp() throws Exception { activity = new DashboardActivity(); } @After public void tearDown() throws Exception { } @Test public void testDashboardHasButtons() { activity.onCreate(null); Button btn1= (Button) activity.findViewById(R.id.btn1); assertNotNull(btn1); Button btn2= (Button) activity.findViewById(R.id.btn2); assertNotNull(btn2); } } 

Testing private methods usually indicates that your design can be improved and is not a specific Robolectric problem.

See this discussion question: How to check a class with private methods, fields, or inner classes?

+7
source share

As with v2 Robolectric, this is not the right way to get started now:

 MyActivity testActivity = new MyActivity(); testActivity.onCreate(null); 

Now the correct way is:

 MyActivity testActivity = Robolectric.buildActivity(MyActivity.class).create().get(); 

This will give you an action instance after calling onCreate.
If you want to test onStart, onResume, onPause, etc., This is the same, just more methods.

 MyActivity testActivity = Robolectric.buildActivity(MyActivity.class).create().start().resume().pause().stop().destroy().get(); 

(add or remove methods in the line of code above to verify the exact instance of the desired action)

Just wanted to clarify a really new nice feature of Robolectric.

+6
source share

All Articles