为什么Toast和Dialogs不能从ActivityInstrumentationTestCase2中运行?

时间:2012-05-03 16:54:54

标签: 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);
    }
}

1 个答案:

答案 0 :(得分:0)

您需要在Application的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();
}

希望这有帮助。