我有AsyncTask类,如下面的代码所示,我正在尝试测试它。 我编写了AsyncTask的测试用例,如下面的测试部分所示,但是如测试代码所示,我只是测试了AsyncTask是否 调用或不调用方法,例如,我没有在doInBackground()中测试代码,因为我不知道如何测试它
请告诉我如何测试AsyncTask类,我们非常感谢任何指南或提示
码
public class AsyncTaskImageLoader extends AsyncTask<String, Void, RequestCreator> {
RequestCreator requCreator = null;
String picUrl = null;
private ImageView mImageView = null;
private UserAdapter.MyViewHolder mHolder = null;
ProgressBar mProgressBar = null;
Validation mValidation = null;
private Context mCtx = null;
public AsyncTaskImageLoader(Context ctx, UserAdapter.MyViewHolder holder) {
mHolder = holder;
mCtx = ctx;
mValidation = new Validation(ctx);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mHolder.progressBar.setVisibility(View.VISIBLE);
}
@Override
protected RequestCreator doInBackground(String... params) {
picUrl = params[0];
if (mValidation.isValidUrl(picUrl)) {
while (!isCancelled() && requCreator == null) {
try {
requCreator = mValidation.requestCreatorFromUrl(picUrl);
} catch (Exception e) {
}
//the value of the delay could be changed preferably
SystemClock.sleep(100);
}
}
return requCreator;
}
@Override
protected void onPostExecute(RequestCreator requestCreator) {
super.onPostExecute(requestCreator);
mHolder.progressBar.setVisibility(View.GONE);
//requestCreator.into(mHolder.imageViewAvatarOfOwner);
mValidation.setImageOnImageView(requestCreator, mHolder.imageViewAvatarOfOwner);
}
测试:
public class AsyncTaskImageLoaderTest {
@Mock
ProgressBar mockProgressBar = null;
@Mock
AsyncTaskImageLoader mockAsyncTaskImageLoader = null;
@Mock
Context mCtx = null;
@Before
public void setUp() {
mCtx = mock(Context.class);
mockProgressBar = mock(ProgressBar.class);
mockAsyncTaskImageLoader = mock(AsyncTaskImageLoader.class);
}
@Test
public void whenProgreeBarISSetToVisibleInOnPreExecute() throws Exception {
mockProgressBar.setVisibility(View.VISIBLE);
verify(mockProgressBar).setVisibility(View.VISIBLE);
}
@Test
public void whenOnDoInBackgroundIsCalled() throws Exception {
String str = new String();
mockAsyncTaskImageLoader.execute(str);
verify(mockAsyncTaskImageLoader).execute(str);
}
@Test
public void whenOnPostExecuteIsCalled() throws Exception {
RequestCreator mockRequestCreator = mock(RequestCreator.class);
mockAsyncTaskImageLoader.onPostExecute(mockRequestCreator);
}
}