[英]doInBackground() not getting executed when called from test class
I'm very new to writing unit tests in Android. 我对在Android中编写单元测试非常陌生。
I have a singleton class as follows 我有一个单例课程,如下
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);
}
}
}
}
For this I have a Test class as follows 为此,我有一个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();
}
}
}
Here mSubject.getTrackName(callback);
在这里
mSubject.getTrackName(callback);
calls the method getTrackName()
in DownloadManager.java
but new DownloadTask().execute();
在
DownloadManager.java
调用方法getTrackName()
,但调用new DownloadTask().execute();
is not invoking doInBackground()
method in asynTask
. 没有在
asynTask
调用doInBackground()
方法。 This leads test case is in infinite loop. 这导致测试用例处于无限循环中。
我认为您必须调用测试Robolectric.flushBackgroundThreadScheduler()来执行asynctask
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.