I have AsyncTask class as shown below in the code, and I am trying to test it. I coded the test cases of the AsyncTask as shown below in the testing section, but as shown in the testing code, I just tested whether or not the AsyncTask methods was called or not, and I did not tested the code in doInBackground() for example, because I do not know how to test it
Please let me know how to test AsyncTask class any guideline or hints are highly appreciated
code
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);
}
testing:
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);
}
}