【发布时间】: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