1

出于某种原因,当从 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);
    }
}
4

1 回答 1

0

您需要在应用程序的 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();
}

希望这可以帮助。

于 2012-05-03T21:36:44.020 回答