android - Robolectric RoboAttributeSet - 如何使用它

标签 android unit-testing robolectric

我有一个自定义的 android View ,它具有我想要测试的可设置样式的属性。我正在尝试使用 RoboAttributeSet 将它们推送到我的 View 的构造函数中,但是对于我的生活来说,我无法找出让它们工作所需的正确语法。无论我尝试什么,在 robolectric 测试中运行时,我推送的属性都不会被 View 拾取。在设备或模拟器上运行该应用程序是可以的。

是否有任何示例可以说明如何使用它们?有谁知道如何做到这一点? 这是我的自定义 View 的代码 fragment 以及它如何使用可设置样式的属性。

TypedArray customProperties = aContext.getTheme().obtainStyledAttributes(aAttrs, R.styleable.LoginView, 0, 0);

try {
  userName.setHint(customProperties.getString(R.styleable.LoginView_username_hint));
} finally {
  customProperties.recycle();
}

这是我的 Robolectric/Spock 单元测试的 fragment ...

given:
AttributeSet attributes = new RoboAttributeSet(
        [new Attribute("com.acme:attr/username_hint", "myhint", "com.acme")], Robolectric.application.resources, LoginView)

when:
view = new LoginView(Robolectric.application, attributes)

then:
view.getUsername().getHint() == "myhint"

谢谢
乔治

最佳答案

对于那些正在使用 RoboElectric 新版本 3 的用户,请从他们的 github 查看这个示例,了解如何使用 ResourceLoader。

https://github.com/robolectric/robolectric/blob/490e5fcb7165bec9ef2ddc1c937af790806bb13d/robolectric/src/test/java/org/robolectric/shadows/ViewStubTest.java#L59

我花了很长时间才找到这样的例子!

编辑:

我只是想更新这个线程,因为在过去的一年里发生了很多变化。谷歌在某种程度上提供了一种关于使用 Android 进行测试的官方文档的方法。你可以找到它

此处:https://google.github.io/android-testing-support-library/

& 此处:https://github.com/googlesamples/android-testing

关于android - Robolectric RoboAttributeSet - 如何使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19945732/

相关文章:

java - RxJava 在多个订阅者之间共享一个 Observable 的发射

android - 创建自己的权限

一天前在特定日期和时间触发的 Android AlarmManager

unit-testing - 在 grails + acegi 中测试 securityConfig 映射

javascript - 如何模拟依赖关系以在 node.js 中进行测试?

android - Robolectric - BuildActivity(MyActivity.class).create() 抛出 NullPointerException

android - Robolectric:setupActivity() 中的 NullPointerException

android - 使用 Retrofit 暂停和恢复下载

c# - 流利的 xml 断言

android - 测试中的 Gradle Robolectric 资源 NotFoundException