我想TDD測試TextView的文本顏色/測試Android的一個TextView的文本顏色。然而,所有的屬性似乎返回0或null,有誰知道爲什麼?使用Robolectric爲Android
的代碼創建文本視圖:
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
}
更新回答評論
我有一個之前的單元測試類調用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()'關於你的測試? – Blundell