我已经用很多不同的方式看了这个,我只剩下了一点头发,我想我会把它放在那里,希望有人已经尝试过了。
我正在尝试为启用 Roboguice 的活动编写 Robolectric 测试。具体来说,我正在尝试编写确保 RadioGroup 行为的测试。
问题在于,在运行测试时,RadioGroup 不像 RadioGroup 并强制执行一次只检查一个 RadioButton 的行为。我可以通过断言和调试器看到我可以一次检查组中的所有三个按钮。
RadioGroup 非常简单:
<RadioGroup
    android:id="@+id/whenSelection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <RadioButton
        android:id="@+id/whenToday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="@string/today" />
    <RadioButton
        android:id="@+id/whenYesterday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/yesterday" />
    <RadioButton
        android:id="@+id/whenOther"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/earlier" />
</RadioGroup>
然后我应该指出我运行应用程序的行为,行为是我所期望的(如果我单击任何一个单选按钮,只有一个保持选中状态,而其他两个未选中)。所以,理论上,这个测试应该通过:
    -- snip--
    Assert.assertTrue(whenToday.isChecked());
    Assert.assertFalse(whenYesterday.isChecked());
    Assert.assertFalse(whenOther.isChecked());
    whenYesterday.performClick();
    Assert.assertTrue(whenYesterday.isChecked());
    Assert.assertFalse(whenToday.isChecked());
    -- snip --
但是,最后一个断言失败了,调试器确认第一个按钮 whenToday 保持选中状态。
这是完整的测试类:
@RunWith(InjectedTestRunner.class)
public class MyTest {
    @Inject ActivityLogEdit activity;
    RadioButton whenToday;
    RadioButton whenYesterday;
    RadioButton whenOther;
@Before
public void setUp() {
    activity.setIntent(new Intent());
    activity.onCreate(null);
    whenSelection = (RadioGroup) activity.findViewById(R.id.whenSelection);
    whenToday = (RadioButton) activity.findViewById(R.id.whenToday);
    whenYesterday = (RadioButton) activity.findViewById(R.id.whenYesterday);
    whenOther = (RadioButton) activity.findViewById(R.id.whenOther);       
}
@Test
public void checkDateSelectionInitialState() throws Exception {
    Assert.assertTrue(whenToday.isChecked());
    Assert.assertFalse(whenYesterday.isChecked());
    Assert.assertFalse(whenOther.isChecked());
    Assert.assertEquals(View.GONE, logDatePicker.getVisibility());
    whenYesterday.performClick();
    Assert.assertTrue(whenYesterday.isChecked());
    Assert.assertFalse(whenToday.isChecked());
  }
}
我已经尝试了我能想到的每一种不同的方式。我觉得我在做一些愚蠢的事情或缺少一些基本概念。请帮忙!
安德鲁