Reputation: 493
i have this class
@Value("${norsys.loadfile.directory}")
private String chemin;
@RequestMapping(value = "/{fileName:.+}", method = RequestMethod.GET)
@ResponseBody()
public void loadVideoFile(@PathVariable("fileName") String fileName,HttpServletResponse response) {
try {
response.setContentType("video/mp4");
Files.copy(Paths.get(chemin, fileName), response.getOutputStream());
response.flushBuffer();
} catch (java.io.FileNotFoundException e) {
response.setStatus(HttpStatus.NOT_FOUND.value());
} catch (Exception e) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
}
I dont know how to apply a JUnit test to keep coverage high, I hope that you can give me an idea, thank you
Upvotes: 1
Views: 294
Reputation: 357
In general you can use Mockito http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html to test classes which have heavyweight dependencies. Using a mock HttpServletResponse class you could verify that the status code is set appropriately for your failure/success cases.
You're going to run into some problems with the use of those static methods.
Instead of
Files.copy(Paths.get(chemin, fileName), response.getOutputStream());
You could use a non-static class, which you could then mock
class ResourceCopier {
public void copy(String dir, String file, OutputStream os) {
Files.copy(Paths.get(dir, file), os);
}
}
Your main class uses
private ResourceCopier resourceCopier;
public void loadVideoFile(....) {
resourceCopier.copy(chemin, fileName, response.getOutputStream());
}
And in your test class you create your primary object, create a Mock of ResourceCopier and HttpServletResponse and use @InjectMocks to inject them to your primary object. You can then use Mockito's verify() method to make sure the right things have happened (like response.setStatus called with 404 code)
Upvotes: 1