How to test java methods that works with excel with JUnit












0















I have methods in Java to work with Excel that I am trying to unit test.
I tried a few things here and there but I doesn't work.



I have the following methods:



@RequestMapping(method = POST, produces = "application/vnd.ms-excel")
@ResponseBody
public ResponseEntity<byte> createExcel(@RequestBody List<ExcelDto> excelDtos) {
log.log(Level.INFO, "generate excel started");
try (InputStream is = GenerateExcelController.class.getResourceAsStream(PATH_TO_TEMPLATE)) {
this.temp = File.createTempFile("tempfile", ".xlsx");
try (FileOutputStream fs = new FileOutputStream(temp)) {
processExcel(excelDtos, is, fs);
return generateResponse();
}
} catch (Exception e) {
log.log(Level.SEVERE, "Cannot generate excel!", e);
}
return null;
}

private void processExcel(List<ExcelDto> productDto, InputStream is, FileOutputStream fs) throws IOException{
Context context = new Context();
context.putVar("products", productDto);
context.putVar("today", LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
JxlsHelper.getInstance().processTemplate(is, fs, context);
}

private ResponseEntity<byte> generateResponse() {
try (FileInputStream fileInputStream = new FileInputStream(temp.getPath())) {
Resource resource = new InputStreamResource(fileInputStream);
byte content = FileCopyUtils.copyToByteArray(resource.getInputStream());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
log.log(Level.INFO, "Download sample .xlsx request completed");
Files.delete(temp.toPath());
return new ResponseEntity<>(content, headers, HttpStatus.OK);
} catch (Exception e) {
log.log(Level.SEVERE, "Cannot find temp excel file!", e);
}
return null;
}


Can someone help me or tell me how to start?










share|improve this question



























    0















    I have methods in Java to work with Excel that I am trying to unit test.
    I tried a few things here and there but I doesn't work.



    I have the following methods:



    @RequestMapping(method = POST, produces = "application/vnd.ms-excel")
    @ResponseBody
    public ResponseEntity<byte> createExcel(@RequestBody List<ExcelDto> excelDtos) {
    log.log(Level.INFO, "generate excel started");
    try (InputStream is = GenerateExcelController.class.getResourceAsStream(PATH_TO_TEMPLATE)) {
    this.temp = File.createTempFile("tempfile", ".xlsx");
    try (FileOutputStream fs = new FileOutputStream(temp)) {
    processExcel(excelDtos, is, fs);
    return generateResponse();
    }
    } catch (Exception e) {
    log.log(Level.SEVERE, "Cannot generate excel!", e);
    }
    return null;
    }

    private void processExcel(List<ExcelDto> productDto, InputStream is, FileOutputStream fs) throws IOException{
    Context context = new Context();
    context.putVar("products", productDto);
    context.putVar("today", LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
    JxlsHelper.getInstance().processTemplate(is, fs, context);
    }

    private ResponseEntity<byte> generateResponse() {
    try (FileInputStream fileInputStream = new FileInputStream(temp.getPath())) {
    Resource resource = new InputStreamResource(fileInputStream);
    byte content = FileCopyUtils.copyToByteArray(resource.getInputStream());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
    log.log(Level.INFO, "Download sample .xlsx request completed");
    Files.delete(temp.toPath());
    return new ResponseEntity<>(content, headers, HttpStatus.OK);
    } catch (Exception e) {
    log.log(Level.SEVERE, "Cannot find temp excel file!", e);
    }
    return null;
    }


    Can someone help me or tell me how to start?










    share|improve this question

























      0












      0








      0








      I have methods in Java to work with Excel that I am trying to unit test.
      I tried a few things here and there but I doesn't work.



      I have the following methods:



      @RequestMapping(method = POST, produces = "application/vnd.ms-excel")
      @ResponseBody
      public ResponseEntity<byte> createExcel(@RequestBody List<ExcelDto> excelDtos) {
      log.log(Level.INFO, "generate excel started");
      try (InputStream is = GenerateExcelController.class.getResourceAsStream(PATH_TO_TEMPLATE)) {
      this.temp = File.createTempFile("tempfile", ".xlsx");
      try (FileOutputStream fs = new FileOutputStream(temp)) {
      processExcel(excelDtos, is, fs);
      return generateResponse();
      }
      } catch (Exception e) {
      log.log(Level.SEVERE, "Cannot generate excel!", e);
      }
      return null;
      }

      private void processExcel(List<ExcelDto> productDto, InputStream is, FileOutputStream fs) throws IOException{
      Context context = new Context();
      context.putVar("products", productDto);
      context.putVar("today", LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
      JxlsHelper.getInstance().processTemplate(is, fs, context);
      }

      private ResponseEntity<byte> generateResponse() {
      try (FileInputStream fileInputStream = new FileInputStream(temp.getPath())) {
      Resource resource = new InputStreamResource(fileInputStream);
      byte content = FileCopyUtils.copyToByteArray(resource.getInputStream());
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
      log.log(Level.INFO, "Download sample .xlsx request completed");
      Files.delete(temp.toPath());
      return new ResponseEntity<>(content, headers, HttpStatus.OK);
      } catch (Exception e) {
      log.log(Level.SEVERE, "Cannot find temp excel file!", e);
      }
      return null;
      }


      Can someone help me or tell me how to start?










      share|improve this question














      I have methods in Java to work with Excel that I am trying to unit test.
      I tried a few things here and there but I doesn't work.



      I have the following methods:



      @RequestMapping(method = POST, produces = "application/vnd.ms-excel")
      @ResponseBody
      public ResponseEntity<byte> createExcel(@RequestBody List<ExcelDto> excelDtos) {
      log.log(Level.INFO, "generate excel started");
      try (InputStream is = GenerateExcelController.class.getResourceAsStream(PATH_TO_TEMPLATE)) {
      this.temp = File.createTempFile("tempfile", ".xlsx");
      try (FileOutputStream fs = new FileOutputStream(temp)) {
      processExcel(excelDtos, is, fs);
      return generateResponse();
      }
      } catch (Exception e) {
      log.log(Level.SEVERE, "Cannot generate excel!", e);
      }
      return null;
      }

      private void processExcel(List<ExcelDto> productDto, InputStream is, FileOutputStream fs) throws IOException{
      Context context = new Context();
      context.putVar("products", productDto);
      context.putVar("today", LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
      JxlsHelper.getInstance().processTemplate(is, fs, context);
      }

      private ResponseEntity<byte> generateResponse() {
      try (FileInputStream fileInputStream = new FileInputStream(temp.getPath())) {
      Resource resource = new InputStreamResource(fileInputStream);
      byte content = FileCopyUtils.copyToByteArray(resource.getInputStream());
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
      log.log(Level.INFO, "Download sample .xlsx request completed");
      Files.delete(temp.toPath());
      return new ResponseEntity<>(content, headers, HttpStatus.OK);
      } catch (Exception e) {
      log.log(Level.SEVERE, "Cannot find temp excel file!", e);
      }
      return null;
      }


      Can someone help me or tell me how to start?







      java unit-testing automated-tests






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 2 at 13:08









      Ayoub RossiAyoub Rossi

      5810




      5810
























          1 Answer
          1






          active

          oldest

          votes


















          0














          @Controller beans are singletons so you must avoid using mutable instance variables e.g. storing temporary file path in this.temp. this.temp is not request scoped, you current approach won't work when there are multiple concurrent POST requests.



          Excel creation logic should probably be extracted to a new @Service bean which can be unit tested with a predefined test resources.



          @Service
          public class ExcelService {

          public OutputStream createExcel(InputStream template, List<ExcelDto> products) {
          // read InputStream
          // process template with JxlsHelper
          // return generated Excel as OutputStream
          }

          }





          share|improve this answer
























          • Or better to change methods signature to return File or filename. In that case it is possible to create a unit-test with some test data, generate Excel file with that test data and then parse it in your unit-test and check that appropriate data was inserted into appropriate cells in tan Excel file

            – Ivan
            Jan 2 at 15:03











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54006959%2fhow-to-test-java-methods-that-works-with-excel-with-junit%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          @Controller beans are singletons so you must avoid using mutable instance variables e.g. storing temporary file path in this.temp. this.temp is not request scoped, you current approach won't work when there are multiple concurrent POST requests.



          Excel creation logic should probably be extracted to a new @Service bean which can be unit tested with a predefined test resources.



          @Service
          public class ExcelService {

          public OutputStream createExcel(InputStream template, List<ExcelDto> products) {
          // read InputStream
          // process template with JxlsHelper
          // return generated Excel as OutputStream
          }

          }





          share|improve this answer
























          • Or better to change methods signature to return File or filename. In that case it is possible to create a unit-test with some test data, generate Excel file with that test data and then parse it in your unit-test and check that appropriate data was inserted into appropriate cells in tan Excel file

            – Ivan
            Jan 2 at 15:03
















          0














          @Controller beans are singletons so you must avoid using mutable instance variables e.g. storing temporary file path in this.temp. this.temp is not request scoped, you current approach won't work when there are multiple concurrent POST requests.



          Excel creation logic should probably be extracted to a new @Service bean which can be unit tested with a predefined test resources.



          @Service
          public class ExcelService {

          public OutputStream createExcel(InputStream template, List<ExcelDto> products) {
          // read InputStream
          // process template with JxlsHelper
          // return generated Excel as OutputStream
          }

          }





          share|improve this answer
























          • Or better to change methods signature to return File or filename. In that case it is possible to create a unit-test with some test data, generate Excel file with that test data and then parse it in your unit-test and check that appropriate data was inserted into appropriate cells in tan Excel file

            – Ivan
            Jan 2 at 15:03














          0












          0








          0







          @Controller beans are singletons so you must avoid using mutable instance variables e.g. storing temporary file path in this.temp. this.temp is not request scoped, you current approach won't work when there are multiple concurrent POST requests.



          Excel creation logic should probably be extracted to a new @Service bean which can be unit tested with a predefined test resources.



          @Service
          public class ExcelService {

          public OutputStream createExcel(InputStream template, List<ExcelDto> products) {
          // read InputStream
          // process template with JxlsHelper
          // return generated Excel as OutputStream
          }

          }





          share|improve this answer













          @Controller beans are singletons so you must avoid using mutable instance variables e.g. storing temporary file path in this.temp. this.temp is not request scoped, you current approach won't work when there are multiple concurrent POST requests.



          Excel creation logic should probably be extracted to a new @Service bean which can be unit tested with a predefined test resources.



          @Service
          public class ExcelService {

          public OutputStream createExcel(InputStream template, List<ExcelDto> products) {
          // read InputStream
          // process template with JxlsHelper
          // return generated Excel as OutputStream
          }

          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 2 at 13:20









          Karol DowbeckiKarol Dowbecki

          24.8k93759




          24.8k93759













          • Or better to change methods signature to return File or filename. In that case it is possible to create a unit-test with some test data, generate Excel file with that test data and then parse it in your unit-test and check that appropriate data was inserted into appropriate cells in tan Excel file

            – Ivan
            Jan 2 at 15:03



















          • Or better to change methods signature to return File or filename. In that case it is possible to create a unit-test with some test data, generate Excel file with that test data and then parse it in your unit-test and check that appropriate data was inserted into appropriate cells in tan Excel file

            – Ivan
            Jan 2 at 15:03

















          Or better to change methods signature to return File or filename. In that case it is possible to create a unit-test with some test data, generate Excel file with that test data and then parse it in your unit-test and check that appropriate data was inserted into appropriate cells in tan Excel file

          – Ivan
          Jan 2 at 15:03





          Or better to change methods signature to return File or filename. In that case it is possible to create a unit-test with some test data, generate Excel file with that test data and then parse it in your unit-test and check that appropriate data was inserted into appropriate cells in tan Excel file

          – Ivan
          Jan 2 at 15:03




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54006959%2fhow-to-test-java-methods-that-works-with-excel-with-junit%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          MongoDB - Not Authorized To Execute Command

          How to fix TextFormField cause rebuild widget in Flutter

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith