How to test java methods that works with excel with JUnit
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
add a comment |
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
add a comment |
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
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
java unit-testing automated-tests
asked Jan 2 at 13:08
Ayoub RossiAyoub Rossi
5810
5810
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
@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
}
}
Or better to change methods signature to returnFileor 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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
@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
}
}
Or better to change methods signature to returnFileor 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
add a comment |
@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
}
}
Or better to change methods signature to returnFileor 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
add a comment |
@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
}
}
@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
}
}
answered Jan 2 at 13:20
Karol DowbeckiKarol Dowbecki
24.8k93759
24.8k93759
Or better to change methods signature to returnFileor 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
add a comment |
Or better to change methods signature to returnFileor 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
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
