如何测试的AsyncTask通过点击触发?测试、AsyncTask

2023-09-07 02:19:40 作者:怎挽

如果在的AsyncTask 通过一个按钮点击事件触发,我怎么能测试它 - 我怎么能等到AsyncTask的完成?

请注意我总是直接在我的测试方法执行的AsyncTask ,我知道如何测试这样的场景。不过,如果我坚持使用模拟使用的onClick 事件 performClick()我还可以测试我的注册过程?

MainActivityFunctionalTest

 公共类MainActivityFunctionalTest扩展            ActivityInstrumentationTestCase2< MainActivity> {    // ...        公共无效testRegistration(){        的ImageButton submitBtn =(的ImageButton)solo.getView(R.id.BtnR);        assertNotNull(submitBtn);        submitBtn.performClick();                //当注册完成后如何做?        }    // ...    } 
C 程序 触发一个中断点

MainActivity (将要测试的项目)

 的ImageButton submitBtn =(的ImageButton)findViewById(R.id.BtnRegister);submitBtn.setOnClickListener(新OnClickListener(){            公共无效的onClick(视图v){                sendRegistration();            }        });公共无效sendRegistration(){        处理器处理器=新处理器(); // AsyncTask的子类        processor.execute();    } 

解决方案

你可以这样做:

  myAsyn的obj =新myAsyn();obj.execute();而(obj.getStatus()== AsynTask.status.Finished){//在这儿等着}//当它完成,这code将要执行。 

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();
    }

解决方案

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.