Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing and Android DownloadManager

I would like to unit test a class that makes use of the Android DownloadManager service, but I'm not sure how to go about doing it. Should I actually use the DownloadManager service or is there some way I can mock it up? I would rather not have my test call an external web server. Is there an existing testing library I can use for this?

like image 378
nil Avatar asked Aug 16 '26 06:08

nil


1 Answers

  1. This solution use Robolectric

One important thing to know is that the count of Download Manager requests starts at -1. So if you enqueue a request, the request count gonna be 0.

  1. Mock your DownloadManager object
  2. Write your test

    public void shouldEnqueueRequest() {
    //...
    
    //...
    
    verify(downloadManager, times(1)).enqueue(anyObject());
    //Is the DownloadManager empty
    assertThat(shadowOf(downloadManager).getRequestCount(), greaterThan(-1));
    //Get the request from the DownloadManager
    ShadowRequest realRequest = shadowOf(shadowOf(downloadManager).getRequest(0));
    assertThat(realRequest, notNullValue());
    assertThat(realRequest.getDescription(), equalTo("Your description"));
    assertThat(realRequest.getTitle(), equalTo(APP_NAME));
    }
    
like image 84
Adrx Avatar answered Aug 18 '26 21:08

Adrx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!