出于某种原因,从 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/