【问题标题】:Testing TextView text colour using Robolectric for Android使用 Robolectric for Android 测试 TextView 文本颜色
【发布时间】:2013-02-06 09:09:07
【问题描述】:

我正在尝试 TDD/测试 android 的 textView 的文本颜色。但是所有属性似乎都返回 0 或 null,有谁知道为什么?

创建文本视图的代码:

public void setupTextView() {

    LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
    TextView textView = new TextView(this);

    textView.setText(job.getName());

    if (job.getLastBuild().getBuildStatus().equals("SUCCESS")) {

        textView.setTextColor(Color.parseColor("#007000"));

    } else {

       textView.setTextColor(Color.parseColor("#FF0000"));

    }

    layout.addView(textView);

}

我已经运行了应用程序,上面的代码可以运行。

我尝试在测试代码中访问的属性:

@Test
public void firstTextViewShouldReflectPassingJobStatus() throws Exception {

    LinearLayout layout = layout = (LinearLayout) activity.findViewById(R.id.layout);

    TextView gomoTextView = (TextView) layout.getChildAt(0);

    System.out.println(gomoTextView.getCurrentTextColor()); //Returns 0
    System.out.println(gomoTextView.getTextColors()); //Returns null
    System.out.println(gomoTextView.getSolidColor()); //Returns 0
    System.out.println(gomoTextView.getCurrentHintTextColor()); //Returns 0

    //I also tried using `Robolectric.shadowOf()`:
    ShadowTextView shadowGomoTextView = Robolectric.shadowOf(gomoTextView);

    System.out.println(shadowGomoTextView.getTextColorHexValue()); //Returns 0
    System.out.println(shadowGomoTextView.getHintColorHexValue()); //Returns null

}

更新以回答 cmets

我在单元测试类中有一个调用onCreate()

private LinearLayout layout;
private HomeActivity activity;

@Before
public void setUp() throws Exception {

    activity = spy(new HomeActivity());
    Jenkins mockJenkins = TestUtilities.getTestJenkins();
    when(activity.getJenkins()).thenReturn(mockJenkins);

    activity.onCreate(null);
    layout = (LinearLayout) activity.findViewById(R.id.layout);

}

还有HomeActivity类中的onCreate方法:

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Jenkins jenkins = getJenkins();
    displayJenkins(jenkins);
}

然后显示詹金斯调用了包括setupTextView()在内的其他方法的负载

【问题讨论】:

  • 如果不查看更多代码,很难确定发生了什么。活动生命周期中的 setupTextView 在哪里调用?您是否确保此生命周期事件在您的测试中发生? (或至少手动调用它!)
  • 是的,你在哪里打电话给setupTextView()

标签: android testing robolectric


【解决方案1】:

期待sources 它尚未实现。我建议您按照here 的描述实现自己的影子。

Robolectric 2.0 已成为 promoted to the alpha state。我认为您的问题应该在发布期间得到解决,因为它们将尽可能多地使用真正的 Android 源代码。

【讨论】:

  • 看起来更新到 2.0 已经对其进行了排序,并且没有引入任何现有测试的任何问题,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-13
  • 1970-01-01
  • 2016-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多