Using Roboletric to build Android Unit Test

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:


    configrationTest.png
  • run


    run.png
  • result


    result.png

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 ()

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容