How to test AsyncTask triggered by a click?

匿名 (未验证) 提交于 2019-12-03 09:18:39

问题:

If the AsyncTask is triggered by a click event on a button, how can I test it - how can I wait until the AsyncTask completes?

Note I can always execute the AsyncTask directly in my test method, I know how to test such scenario. However, if I insist on on using simulating the onClick event using performClick() can I still test my registration process?

MainActivityFunctionalTest

public class MainActivityFunctionalTest extends             ActivityInstrumentationTestCase2<MainActivity> {     // ...         public void testRegistration() {         ImageButton submitBtn = (ImageButton) solo.getView(R.id.BtnR);         assertNotNull(submitBtn);           submitBtn.performClick();                 // How to do something when the registration is done?         }     // ...     }  

MainActivity (of the project to be tested)

ImageButton submitBtn = (ImageButton) findViewById(R.id.BtnRegister); submitBtn.setOnClickListener(new OnClickListener() {             public void onClick(View v) {                 sendRegistration();             }         });  public void sendRegistration() {         Processor processor = new Processor();// subclass of AsyncTask         processor.execute();     } 

回答1:

you can do :

myAsyn obj = new myAsyn(); obj.execute();  while(obj.getStatus()==AsynTask.status.Finished) { //wait here }  //when it finishes , this code will going to execute. 


回答2:

you can also use get() method to wait until task complete. http://developer.android.com/reference/android/os/AsyncTask.html#get%28%29



回答3:

Use your Activity from your ActivityTestCase. Find the view by id and simply send the event to your view.

More info on runTestOnUiThread:

private void buttonTest(Activity activity, int buttonId){    Button button = (Button) activity.findViewById(buttonId);     assertNotNull("Button not allowed to be null", button);     button.performClick(); }  private void runButtonTest(Activity activity, int buttonId){        getInstrumentation().runTestOnUiThread(new Runnable() {             public void run() {                 buttonTest(activity,buttonId);             }      Object o = activity.mAsyncTask.get();      assertNotNull(o); } 

Alternatively you can wait until Status of the AsyncTask changes to Status.Finished.



回答4:

You can check the status of the asynctask using that you can perform your operations for more details check the link below

http://developer.android.com/reference/android/os/AsyncTask.Status.html



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!