与 Robolectric 合作,我对 android 很陌生。我使用 Activity 创建了第一个测试类。它工作得很好。现在我想对片段进行测试。
@RunWith(RobolectricTestRunner.class)
public class LoginFragmentTest {
private LoginFragment fragment;
@Before
public void setup() {
fragment = new LoginFragment();
startFragment(fragment);
assertThat(fragment, notNullValue());
assertThat(fragment.getActivity(), notNullValue());
}
private void startFragment(LoginFragment fragment) {
FragmentManager fragmentManager = new FragmentActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(fragment, null);
fragmentTransaction.commit();
}
@Test
public void login() {
EditText idEditText = (EditText)fragment.getActivity().findViewById(R.id.main_id);
assertThat(idEditText, notNullValue());
}
}
这是我的第一个片段类测试类。它抛出
"java.lang.IllegalStateException: Activity has been destroyed" in startFragment#fragmentTransaction.commit().
任何人都知道如何解决这个问题?
您可以从https://github.com/msbaek/frame-test找到整个源代码
提前致谢 !!