我正在开发一个Android应用。我正在为Android编写Junit测试,并且是Junit测试用例的新手。
在应用内,单击时有一个相对的布局,即打开日期选择器对话框,一旦用户选择了要在TextView中显示的日期,就可以了。
我想用Junit测试这些动作。当我尝试运行测试用例时,它向我抛出以下错误:
java.lang.RuntimeException: Can't create handler inside thread Thread[Instr: androidx.test.runner.AndroidJUnitRunner,5,main] that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:205)
at android.os.Handler.<init>(Handler.java:118)
at android.app.Dialog.<init>(Dialog.java:123)
at android.app.AlertDialog.<init>(AlertDialog.java:201)
at android.app.AlertDialog.<init>(AlertDialog.java:197)
at android.app.DatePickerDialog.<init>(DatePickerDialog.java:115)
at android.app.DatePickerDialog.<init>(DatePickerDialog.java:90)
at com.example.sride.DataSelectedTest.loginClickedSuccess(DataSelectedTest.java:74)
这是我的测试班:
@RunWith(AndroidJUnit4ClassRunner.class)
public class DataSelectedTest {
private Context appContext;
@Test
public void useAppContext() {
// Context of the app under test.
appContext = ApplicationProvider.getApplicationContext();
assertEquals("com.example.sride", appContext.getPackageName());
}
@Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void datCheckSuccess() throws Throwable {
Log.e("@Test", "Performing date check success test");
Espresso.onView((withId(R.id.calendarRl)))
.perform(ViewActions.click());
// throwing error at this line
// If I remove this line then it is working as expected
DatePickerDialog datePickerDialog =
new DatePickerDialog(mActivityRule.getActivity(), null, 2012, 6, 7);
datePickerDialog.dismiss();
Espresso.onView(withId(R.id.dateTv))
.check(matches(withText("7" + "-" + (6 + 1) + "-" + "2012")));
}
}
我也尝试过将这些代码在runOnUiTHeard()
内部运行,但问题仍然存在。
我也尝试过将这些代码在Handler()
内部运行,但测试将继续运行而不显示任何输出
我想念什么吗?
这里是一个可以解决您问题的链接。要处理您的活动的真实实例,您将需要进行仪器测试或可能需要使用Roboelectric。