【问题标题】:AndroidJUnit4ClassRunner throwing RuntimeException AndroidAndroidJUnit4ClassRunner 抛出 RuntimeException Android
【发布时间】:2023-03-24 23:47:02
【问题描述】:

我正在开发一个 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() 中运行这些代码,但测试将继续运行,不显示任何输出

我错过了什么吗?

【问题讨论】:

  • The answer 是旧的,但可能会有所帮助。
  • @Onik 我试过了,但它是无限的

标签: android junit4 handler android-junit androidjunitrunner


【解决方案1】:

这是一个可以解决您问题的链接。要处理您的活动的真实实例,您需要进行仪器测试,或者您可能需要使用 Roboelectric。

Instrumented Unit Class Test - Can't create handler inside thread that has not called Looper.prepare()

【讨论】:

    猜你喜欢
    • 2012-11-23
    • 2015-01-25
    • 2018-07-10
    • 2011-10-02
    • 1970-01-01
    • 2014-09-27
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多