如何在 robolectric 中使用 findViewById()

2023-11-26

我只是想用 robolectric 测试某个视图在片段中是否可见。 我的单元测试如下所示:

ActivityController controller = Robolectric.buildActivity(FragmentActivity.class);
FragmentActivity activity = (FragmentActivity) controller.create().start().resume().visible().get();

F fragment = new MyFragment();
activity.getSupportFragmentManager().beginTransaction()
        .add(fragment, FRAGMENT_TAG).commit();


View view = fragment.getView().findViewById(R.id.my_view);
assertEquals(view.getVisibility(), View.VISIBLE);

我正在使用最新的 android gradle 插件 1.1.3、robolectirc 2.4 和 robolectric gradle 插件 1.0.1,我的单元测试位于test文件夹(不是androidTest)。我无法编译该代码,因为编译器无法解析R.java.

My build.gradle:

buildscript {
  repositories {
    jcenter()
  }

  dependencies {
    classpath 'com.android.tools.build:gradle:1.1.3'
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
    classpath 'org.robolectric:robolectric-gradle-plugin:1.0.1'
  }
}

apply plugin: 'com.android.library'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: 'org.robolectric'


android { ... }

dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])

  // Testing
  testCompile 'org.robolectric:robolectric:2.4'
  testCompile 'junit:junit:4.12'

  // Other dependencies
  ...
}

如何使用 robolectric 编写这样的单元测试?

更新: 这是完整的代码:

public class TestFragment extends Fragment {

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_listview_ptr, container, false);
  }
}


public class MyFragmentTest {

  private static final String FRAGMENT_TAG = "fragment";
  private ActivityController controller;
  private FragmentActivity activity;

  @Test
  protected void displaysContentView(boolean pullToRefreshSupported) {

    controller = Robolectric.buildActivity(FragmentActivity.class);
    activity = (FragmentActivity) controller.create().start().resume().visible().get();
    Fragment fragment = new TestFragment();

    FragmentManager manager = activity.getSupportFragmentManager();
    manager.beginTransaction()
        .add(fragment, FRAGMENT_TAG).commit();

    // Compile errors here
    View loadingView = fragment.getView().findViewById(R.id.loadingView);
    View contentView = fragment.getView().findViewById(R.id.contentView);
    View errorView = fragment.getView().findViewById(R.id.loadingView);

    Assert.assertNotSame(loadingView.getVisibility(), View.VISIBLE);
    Assert.assertNotSame(errorView.getVisibility(), View.VISIBLE);
    Assert.assertEquals(contentView.getVisibility(), View.VISIBLE);
  }
}

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">


<android.support.v4.widget.SwipeRefreshLayout
      android:id="@+id/pull_to_refresh"
      android:layout_width="match_parent"
      android:layout_height="match_parent">

    <ListView
        android:id="@+id/contentView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:cacheColorHint="#00000000"
        android:divider="@null"
        android:fadingEdge="none"
        android:fastScrollEnabled="false"
        android:footerDividersEnabled="false"
        android:headerDividersEnabled="false"
        android:listSelector="@color/transparent"
        android:drawSelectorOnTop="true"
        android:smoothScrollbar="false"
        android:scrollbars="none"/>
</android.support.v4.widget.SwipeRefreshLayout>

<TextView
      android:id="@+id/errorView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:visibility="gone"
      android:text="@string/error_loading_retry"
      android:layout_gravity="center"
      android:gravity="center"
      android:layout_centerInParent="true"
      android:drawableTop="@drawable/error_no_connection"
      android:drawablePadding="12dp"
      android:textColor="@color/gray_dark"
      android:padding="16dp"
      />

<fr.castorflex.android.circularprogressbar.CircularProgressBar
      android:id="@+id/loadingView"
      android:layout_width="40dp"
      android:layout_height="40dp"
      android:indeterminate="true"
      android:layout_gravity="center"
      android:layout_centerInParent="true"
      android:visibility="gone"
      />

</FrameLayout>

代码可以在这里找到:https://github.com/sockeqwe/RobolectircTest


Update:

我建议继续更新到 Robolectric 3.0。

用以下内容注释你的类:

@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

更新您的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'
    }
}

原来的:

Using Robolectric.buildActivity(FragmentActivity.class);用于测试Activitys.

请编辑您的MyFragmentTest看起来像这样:

@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);
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 robolectric 中使用 findViewById() 的相关文章

随机推荐

  • C++ 中的抽象类声明

    Suppose foo is an abstract class在 C 程序中 为什么可以接受声明类型的变量foo 但不是类型foo 因为如果你声明一个 foo 你必须初始化 实例化它 如果声明 foo 则可以使用它来指向继承自 foo 但
  • 如何在Tradingview上的pinescript中在某个时间绘制垂直线?

    我想在每天的某个当地时间 例如 08 00 GMT 1 画一条垂直线 自从我的最后发表关于垂直线 pine script 已更新为包括vline 然而 这里的问题是如何把握正确的时间 大多数服务器 针对外汇 似乎都位于美国 并且交易视图本地
  • 在 Keras 中获取预测

    我已经在 Keras 中成功训练了一个简单的模型来对图像进行分类 model Sequential model add Convolution2D 32 3 3 border mode valid input shape img chann
  • 非静态变量 this 不能从静态上下文中引用 - 为什么在这里?

    我有一个代码 package why public class Foo public class Foo1 String bar public Foo1 String bar this bar bar public static Foo1
  • PHPUnit、PEAR 升级错误

    注 我读过关于这个问题的所有问题 PEAR 已在我的系统 Ubuntu 11 10 Apache 2 2 20 上安装和配置 因为 返回这个 bool true PEAR 手册 检查 PEAR 是否工作第 4 步 当我尝试使用 phpuni
  • 使用 JavaScript MV* 框架的原因? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心以获得指导 我有一个电子商务网站 它需
  • 多核安卓

    我运行了简单的并行算法 绘制了 mandelbrot 集 以在 Nexus 7 Tegra 3 4 1 核心 上测试并行计算 运行几次后 串行速度为 1 5 秒 并行速度为 1 0 秒 但并行和串行速度非常接近 均为 1 3 秒 正方形是7
  • 创建共享 HSQLDB 数据库

    进程内 HSQLDB 数据库不应被其他人打开 即使对于基于文件的存储也是如此 文档暗示这是可能的 服务器模式 高级主题 但我还没有找到如何激活此行为的 URL 有没有人这样做过 以便分享如何做 以下对我有用 从您的代码启动服务器 如 HSQ
  • 防止元素的最后一个单词与另一个元素之间出现换行

    给定一个具有可变长度文本的内联 或内联块 元素 以及第一个元素右侧的另一个元素充当一种徽章 是否有一种方法可以防止第一个元素的最后一个单词之间出现换行符元素和第二个元素 两个元素占据同一行就可以了 第一个元素的文本中出现换行也可以 但两个元
  • 如何在 React Native 中使用 CSS

    我可以用吗CSS为我的造型反应本机成分 目前我只能使用样式表像这样 var styles React StyleSheet create autocomplete backgroundColor FFF zIndex 5 我想使用 CSS
  • 我可以使用链式比较运算符语法吗? [复制]

    这个问题在这里已经有答案了 在一个 JS 库中我看到这样的语法 if val gt 5 t 我在控制台中测试了这个 1 1 2 false 2 gt 1 1 true 1 2 1 false 1 1 1 true 1 lt 2 lt 3 t
  • TextView 字符串中的 HTML 标签

    如果我将简单的 HTML 格式标记 例如 放入字符串资源中并在 TextView 中显示该字符串 则会应用预期的格式 但是 如果我构建自己的字符串并显示它 我该如何做到这一点呢 如果我执行类似 String str This is bold
  • 摆脱 元素周围的填充/边距?

    我在 div 中有一个画布对象 画布周围似乎有某种填充物 我希望它的边缘接触浏览器屏幕的边缘 my html file div div my java gwt code Canvas canvas Canvas createIfSuppor
  • 如何在 Windows Phone 上运行并行任务?

    我正在构建一个 WP8 应用程序 需要执行大约 30 个网络请求 这些请求彼此不依赖 因此可以并行化 我的代码如下所示 简化 伪代码 foreach Uri uri in uris var rawData await Task Run gt
  • FullCalendar 结束日期不包括在内

    我正在使用 FullCalendar Beta2 并将 AllDay 标志设置为 True 日历仍然将结束日期视为排他日期 如何使结束日期包含在内 非常感谢 ZooZ 根据 Beta 2 升级文档 结束日期现在是唯一的 所有结束日期现在都是
  • Django loaddata - 内存不足

    我使用以下命令转储了我的数据库dumpdata它创建了一个 500mb 的 json 文件 现在我正在尝试使用loaddata恢复数据库 但似乎 Django 尝试在应用它之前将整个文件加载到内存中 并且我收到内存不足错误并且进程被终止 难
  • 如何制作这样一个带有渐变和透明的有角度的箭头?

    如何制作这样一个带有渐变和透明的有角度的箭头 我在这里做了一个带有渐变的块 需要帮助才能转换为箭头 http jsfiddle net jitendravyas aZ65c 2 我需要一个兼容ie8的兼容机 jitendar 看看我用纯CS
  • SQL 中外连接的目的(或用例)是什么?

    外连接仅用于开发人员的分析吗 我无法找到一个用例来解释为什么您想要在两个或多个不相关或不 匹配 您的选择条件的表中包含数据 一个示例用例是生成一个显示所有客户及其购买情况的报告 也就是说 甚至向未购买任何商品的顾客展示 如果您对客户和购买进
  • Rcpp - 在 sourceCpp 引用的文件中使用多个 C++ 函数?

    我希望这不是太明显 因为我已经搜索了一整天但找不到答案 假设我有以下 R 文件 library Rcpp sourceCpp cfile cpp giveOutput c 1 2 3 它编译以下 C 文件 include
  • 如何在 robolectric 中使用 findViewById()

    我只是想用 robolectric 测试某个视图在片段中是否可见 我的单元测试如下所示 ActivityController controller Robolectric buildActivity FragmentActivity cla