我正在开发一个 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()
但测试将继续运行,不显示任何输出
我错过了什么吗?