我非常擅长在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);
调用getTrackName()
中的方法DownloadManager.java
,但new DownloadTask().execute();
未调用doInBackground()
中的asynTask
方法。这导致测试用例处于无限循环中。
答案 0 :(得分:0)
我认为你必须调用你的测试Robolectric.flushBackgroundThreadScheduler()来执行你的asynctask