title: How to do Mockito unit test on method which has a return value ResponseEntity<byte[]>?
body: <p>I'm new to testing and Mockito. However, not so new in working Spring.</p>
  <p>I have a service layer implementation of <code>exportResource(String id, String fileType, Class resourceClass) throws MyCustomEx1, MyCustomEx2</code>. My assignment is to create a unit test with Mockito for <code>exportResource()</code> which is downloading a file directly from browser or throws exception if for some reason reaching to <code>ResponseEntity</code> return statement is not successfull.</p>
  <p>Here is a rough overview of a service layer class where <code>exportResource()</code> is living;</p>
  <pre><code>@Service
  @AllArgsConstructor
  public class ExportImportServiceImpl implements ExportImportService {
  
      private final FhirRepository fhirRepository;
      private final CtsConfig ctsConfig;
  
      @Override
      public ResponseEntity&lt;byte[]&gt; exportResource(String id, String fileType, Class resourceClass) throws throws MyCustomEx1, MyCustomEx2 {
  
          if (fileType == null ) throw new MyCustomEx1();
  
          Bundle bundle = (Bundle) fhirRepository.resourcesWithCriterion(resourceClass, DaoConstants.ID, null).get();
  
          if (bundle != null &amp;&amp; bundle.hasEntry()) {
  
              Optional&lt;Bundle.BundleEntryComponent&gt; resource =
                      bundle.getEntry()
                              .stream()
                              .filter(filter -&gt; resourceClass.isInstance(filter.getResource()))
                              .findFirst();
              if (resource.isPresent()) {
                  IBaseResource castedResource = (IBaseResource) resourceClass.cast(resource.get().getResource());
  
                  IParser parser = null;
                  MediaType mt = null;
  
                  if (fileType.equalsIgnoreCase(&quot;json&quot;)){
                      mt = MediaType.APPLICATION_JSON;
                      parser = fhirRepository.jsonParser();
                  } else if (fileType.equalsIgnoreCase(&quot;xml&quot;)){
                      mt = MediaType.APPLICATION_XML;
                      parser = fhirRepository.xmlParser();
                  } else throw new MyCustomEx1();
  
                 
                  parser.setPrettyPrint(true);
  
                  var serializedResource = parser.encodeResourceToString(castedResource);
  
                  return ResponseEntity
                          .ok()
                          .header(HttpHeaders.CONTENT_DISPOSITION,&quot;attachment;&quot; + &quot;filename=&quot; + resourceClass.getSimpleName() + &quot;-&quot; + castedResource.getId() + &quot;.&quot; + fileType)
                          .contentType(mt)
                          .contentLength(serializedResource.getBytes(StandardCharsets.UTF_8).length)
                          .body(serializedResource.getBytes(StandardCharsets.UTF_8));
              }
  
          }
  
          throw new MyCustomEx2();
      }
  
  
      //other implementations here...
  }
  </code></pre>
  <p>I do understand (by wastching some tutorials etc) that we can use Mockito to mock external services/repositories, to verify if some method is getting called, to mock some return values etc. But I'm confused about if-else parts in my business logic-code. Namely, the part:</p>
  <pre><code>if (bundle != null &amp;&amp; bundle.hasEntry()) {
      
                  Optional&lt;Bundle.BundleEntryComponent&gt; resource =
                          bundle.getEntry()
                                  .stream()
                                  .filter(filter -&gt; resourceClass.isInstance(filter.getResource()))
                                  .findFirst();
                  if (resource.isPresent()) {
                      IBaseResource castedResource = (IBaseResource) resourceClass.cast(resource.get().getResource());
      
                      IParser parser = null;
                      MediaType mt = null;
      
                      if (fileType.equalsIgnoreCase(&quot;json&quot;)){
                          mt = MediaType.APPLICATION_JSON;
                          parser = fhirRepository.jsonParser();
                      } else if (fileType.equalsIgnoreCase(&quot;xml&quot;)){
                          mt = MediaType.APPLICATION_XML;
                          parser = fhirRepository.xmlParser();
                      } else throw new ByException(ByErrorCode.ERR_BY_1013);
      
                     
                      parser.setPrettyPrint(true);
      
                      var serializedResource = parser.encodeResourceToString(castedResource);
  </code></pre>
  <p>I don't understand how to write test to handle if-else part. I mean, isn't too simple to test something like that?</p>
  <p>Here is what I (sadly) got:</p>
  <pre><code>  @Test
    void exportCodeSystem() throws Exception {
  
      String id = &quot;32&quot;;
  
      verify(this.fhirRepository.resourcesWithCriterion(ValueSet.class, DaoConstants.ID, null));
  
  
      Mockito.when(
              controller.exportCodeSystem(Mockito.anyString(),Mockito.anyString())
      ).thenReturn(ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).build());
  
  
      RequestBuilder request = MockMvcRequestBuilders.get(&quot;/url-to-controller&quot;)
                                                     .param(&quot;id&quot;,&quot;32&quot;)
                                                     .param(&quot;file-type&quot;, &quot;json&quot;);
  
      MvcResult result = mockMvc.perform(request).andReturn();
      Assertions.assertFalse(result.getResponse().getStatus() == 200);
  
    }
  </code></pre>
  <p>This throws some error. But that is not important as to how to write meaningful unit test in this case? Or even better, how to write code which can be easily unit-tested?</p>
  <p><strong>UPDATE 1</strong></p>
  <p>This is how my test looks now:</p>
  <pre><code>@Test
    void exportCodeSystem() throws Exception {
  
      CompletableFuture&lt;Bundle&gt; completedFuture = CompletableFuture.completedFuture(this.codeSystemBundle);
  
      Mockito.when(this.fhirRepository.resourcesWithCriterion(ArgumentMatchers.&lt;Class&lt;CodeSystem&gt;&gt;any(),
              ArgumentMatchers.&lt;ICriterion&lt;? extends IParam&gt;&gt;any(),
              eq(null)))
              .thenReturn(completedFuture);
  
      MvcResult  result = mockMvc.perform(MockMvcRequestBuilders.
              get(&quot;/code-system/export&quot;)
              .param(&quot;id&quot;, &quot;32&quot;).param(&quot;file-type&quot;, &quot;json&quot;))
              .andExpect(MockMvcResultMatchers.status().isOk())
              .andExpect(MockMvcResultMatchers.content().contentType(&quot;application/json&quot;)).andReturn();
  
      Assertions.assertEquals(result.getResponse().getStatus(), HttpStatus.OK.value());
    }
  </code></pre>
  <p>I keep getting NPE on the line where <code>MvcResult result ..</code> is. What I want to achive with test? I don't know to be honest. I'm trying to test in a some meaningful way, but I don't think I understand how to achieve that.</p>
  <p>This is how controller looks like:</p>
  <pre><code>@AllArgsConstructor
  @RestController
  @RequestMapping(&quot;/code-system&quot;)
  public class CodeSystemController {
  
    private final ExportImportService exportImportService;
  
  @GetMapping(&quot;/export&quot;)
  public boolean exportCodeSystem(@RequestParam(&quot;id&quot;) String id, @RequestParam(&quot;file-type&quot;) String fileType) throws IOException, ByException{
  
      return this.exportImportService.exportResource(id, fileType, CodeSystem.class);
  }
  
  }
  </code></pre>