How to use findViewById() in robolectric

被刻印的时光 ゝ 提交于 2019-11-30 07:27:58

Update:

I would suggest to go ahead and update to Robolectric 3.0.

Annotate your classes with:

@RunWith(CustomRobolectricRunner.class)
@Config(emulateSdk = 21, reportSdk = 21)

RobolectricGradleTestRunner.java:

https://github.com/nenick/AndroidStudioAndRobolectric/blob/master/app/src/test/java/com/example/myapplication/CustomRobolectricRunner.java

Update your build.gradle:

apply plugin: 'com.android.application' // <-- for some reason, com.android.library is not working correctly
apply plugin: 'org.robolectric'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.0"

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:22.0.0'

    testCompile 'junit:junit:4.12'
    testCompile 'org.apache.maven:maven-ant-tasks:2.1.3'
    testCompile('org.robolectric:shadows-support-v4:3.0-SNAPSHOT') {
        exclude group: 'commons-logging', module: 'commons-logging'
        exclude group: 'org.apache.httpcomponents', module: 'httpclient'
    }
}

Original:

Using Robolectric.buildActivity(FragmentActivity.class); is for testing Activitys.

Please edit your MyFragmentTest to look like this:

@RunWith(CustomRobolectricRunner.class)
@Config(emulateSdk = 21, reportSdk = 21)
public class MyFragmentTest {

  @Test
  public void testAppFragmentStart() {
    final TestFragment fragment = new TestFragment();

    SupportFragmentTestUtil.startFragment(fragment, FragmentActivity.class);

    // My test examples - hamcrest matchers
    Assert.assertThat(fragment, CoreMatchers.not(CoreMatchers.nullValue()));
    Assert.assertThat(fragment.getView(), CoreMatchers.not(CoreMatchers.nullValue()));
    Assert.assertThat(fragment.getActivity(), CoreMatchers.not(CoreMatchers.nullValue()));
    Assert.assertThat(fragment.getActivity(), CoreMatchers.instanceOf(FragmentActivity.class));

    // Your tests
    View loadingView = fragment.getView().findViewById(R.id.loadingView);
    View contentView = fragment.getView().findViewById(R.id.contentView);
    View errorView = fragment.getView().findViewById(R.id.errorView);

    Assert.assertNotSame(loadingView.getVisibility(), View.VISIBLE);
    Assert.assertNotSame(errorView.getVisibility(), View.VISIBLE);
    Assert.assertEquals(contentView.getVisibility(), View.VISIBLE);
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!