簡體   English   中英

從測試類調用doInBackground()不會執行

[英]doInBackground() not getting executed when called from test class

我對在Android中編寫單元測試非常陌生。

我有一個單例課程,如下

public enum DownloadController {
    INSTANCE;

    private AsyncTask<?, ?, ?> mRunningTask;

    /*
    * @param LoginListener
    * Request for getting full name of an user.
    * */
    public void getTrackName(DownloadListener listener){
        if(mRunningTask != null) mRunningTask.cancel(true);
        mListener = listener;
        mRunningTask = new DownloadTask();
        try {
            mRunningTask.execute();
        }catch (Exception e){
            e.getLocalizedMessage();
        }
    }

    //Task which gets us the full name of an user
    public class DownloadTask extends AsyncTask<Void, Void, String> {

        @Override
        public String doInBackground(Void... params) {
            String trackName;
            try {
                trackName = getTrackName();
            } catch (VolleyError | AuthException volleyError) {
                trackName = "error"
            }
            return trackName;
        }

        @Override
        public void onPostExecute(String name) {
            if (mListener != null) {
                mListener.onNameObtained(name);
            }
        }
    }
}

為此,我有一個Test類,如下所示

@RunWith(PowerMockRunner.class)
@PrepareForTest({DownloadController.class})
@Config(constants = BuildConfig.class, emulateSdk = 19, manifest="src/main/AndroidManifest.xml")
public class DownloadControllerTest {

    DownloadController mSubject;
    String mTrackName;


    @Before
    public void setUp() {
        mSubject = DownloadController.INSTANCE;
    }

    @Test
    public void getTrackName_test() throws InterruptedException, AuthException, VolleyError {
        // execute
        final DownloadCallback callback = new DownloadCallback();
        mSubject.getTrackName(callback);
        callback.blockForResult();
        // verify
        assertThat(callback.mTrackName, is("Track1"));
    }

    private class DownloadCallback implements DownloadListener {
        CountDownLatch mLatch = new CountDownLatch(1);
        String mFullname;

        @Override
        public void onNameObtained(String fullName) {
            mFullname = fullName;
            mLatch.countDown();
        }

        public void blockForResult() throws InterruptedException {
            mLatch.await();
        }
    }
}

在這里mSubject.getTrackName(callback); DownloadManager.java調用方法getTrackName() ,但調用new DownloadTask().execute(); 沒有在asynTask調用doInBackground()方法。 這導致測試用例處於無限循環中。

我認為您必須調用測試Robolectric.flushBackgroundThreadScheduler()來執行asynctask

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM