Robolectric is a unit test framework that de-fangs the Android SDK jar so you can test-drive the development of your Android app. Tests run inside the JVM on your workstation in seconds
Configration
Add the following dependency to the Gradle build file:
testCompile 'org.mockito:mockito-core:1.9.5'
testCompile "org.robolectric:robolectric:3.1.1"
testCompile 'junit:junit:4.12'
make a dir: D:\denali\scout4cars\Android-Java\HMI\src\test\java\com\telenav\arp
The package path to the test must be the same as src / main / java / {packageName} so that android studio can recognize the unit test directory
Example
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = com.telenav.arp.app.BuildConfig.class, sdk = 22)
public class EntityDetailFragmentUnitTest {
@Before
public void setup(){
MainActivity mainActivity= Robolectric.buildActivity(MainActivity.class).get();
DisplayManager.getInstance().setActivity(mainActivity);
}
@Test
public void testOnCreateView() throws Exception {
EntityDetailFragment fragment=new EntityDetailFragment();
startFragment(fragment);
// check title label
TextView textView = (TextView) ReflectUtil.getFieldValue(fragment, "mTitle");
assertEquals(fragment.getActivity().getString(R.string.entityDetailTitle), textView.getText().toString());
}
-
setup the test:
-
run
-
result
Using motiko for mocking objects
@Test
public void testOnPageHide() throws Exception {
EntityDetailFragment mock = mock(EntityDetailFragment.class);
doCallRealMethod().when(mock).onPageHide();
mock.onPageHide();
verify(mock, atLeastOnce()).clearMap();
}
mock a class, then set the preconditions, and finally verify that the clearMap () method was executed at least once while executing onPageHide ()