问题
I am using Robotium to automate testing of an application. Is there a way I can display an alert box while executing a particular test case.
Thanks.
回答1:
It is possible to do, nearly everything is possible but before I give you the answer do you have a good reason to do this? I cant easily thing of a good reason why a test should open an alert box but you may know best.
Robotium has the method.
solo.getCurrentActivity();
Using this you can get an Activity Context and with such a thing you can do pretty much anything that you could do in an android activity. The page http://developer.android.com/guide/topics/ui/dialogs.html tells us how to make a dialog, you will notice the first line calls a method to get the currentActivity, instead of that I replaced it with the robotium method above.
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(solo.getCurrentActivity());
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(R.string.dialog_message)
.setTitle(R.string.dialog_title);
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
this will create a dialog, then just call the dialogs .show() method to show it on the screen.
回答2:
Robotium tests do not run on the UI Thread, so any code in a test method will in the best case just not work and in the worst case throw and error and cause your test to fail.
To interact with the UI from inside a test method you need to run your code on the UI Thread. This can be done by writing that code inside a Runnable, and sending that Runnable to the runOnUiThread()
method of the current Activity. Robotium's solo class has the getCurrentActivity()
method, which will allow this execution. Here's an example of how you'd show a Toast using this technique.
public void testDisplayToastInActivity() throws Exception
{
Runnable runnable = new Runnable
{
@Override
public void run()
{
Toast.makeText(solo.getCurrentActivity(), "Hello World", Toast.LENGTH_LONG).show();
}
}
solo.getCurrentActivity().runOnUiThread(runnable);
}
You can use runOnUiThread()
to perform many other actions that interact with your Activity, such as creating Alert Dialogs, if you want something more than a Toast. However, I'd suggest against doing any of this, even though you can. Robotium and other testing frameworks are meant to judge the correctness of your application code's execution, and should not inject any logic or UI modifying behavior beyond interacting with your application the way a user would. Your tests will be cleaner if you take any outpu from your tests and log them to Logcat or a file.
来源:https://stackoverflow.com/questions/14252604/display-alert-dialog-while-running-an-android-test-case