android - 为什么 Toasts 和 Dialogs 在 ActivityInstrumentationTestCase2 中不起作用?

标签 android testing

出于某种原因,从 ActivityInstrumentationTestCase2 类中的测试方法调用 Toast.makeText().show() 和 dialog.show() 调用时不执行任何操作。

有谁知道为什么或如何解决这个问题?

例子:

public class MyTest extends ActivityInstrumentationTestCase2<MyActivity> {

    public MyTest(String name)
    {
        super("com.mypackage.activities", MyActivity.class);
        setName(name);
    }

    public exampleTest()
    {
        //This works to show that the test class is running correctly
        TouchUtils.drag(this, 200.0F, 200.0F, 300.0F, 300.0F, 5);

        //The following line does nothing
        Toast.makeText(getActivity(), "toast message", Toast.LENGTH_LONG).show();

        //Sleep to make sure we can see the message
        SystemClock.sleep(5000);
    }
}

最佳答案

您需要在应用程序的 UI 线程上执行您的代码:

MyActivity myActivity = getActivity();

// create a toast on application's ui thread.
// you can also use getInstrumentation().runOnMainSync() here.
myActivity.runOnUiThread(new Runnable() {
  public void run() {
    Toast.makeText(myActivity, "toast message", Toast.LENGTH_LONG).show();
  }
});

// wait a second to see the effect.
try {
  Thread.sleep(1000);
} catch (InterruptedException e) {
  e.printStackTrace();
}

希望这对您有所帮助。

关于android - 为什么 Toasts 和 Dialogs 在 ActivityInstrumentationTestCase2 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10435929/

相关文章:

java - Cardview 不显示在 android studio 3.5.1

java - 在 Android 应用程序中导入 Java 项目?

java - 从 JAXB 迁移到 Castor 的简单方法?

testing - 没有软件就无法调试硬件吗?

C# ASP.Net Selenium 随机点击

testing - 在运行时跳过 RSpec 测试用例

java - Android - 按钮计时器(处理程序 - RemoveCallback 不会停止 PostDelayed)

java - sipdroid - 在继续时不显示另一个来电

javascript - Cypress 测试 : How To Compare Count Of Elements Before & After AJAX Call

reactjs - react : Is it bad practice to import a child component directly rather than pass in as a dependency?