我有一个带有方法的简单控制器:
@ResponseBody
@RequestMapping(value = "/{" + WebConstants.ATTACHMENT_ID + "}", method = RequestMethod.GET)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public void getAttachmentById(@PathVariable(value = WebConstants.ATTACHMENT_ID) Integer attachmentId,
HttpServletResponse response) throws IOException {
logger.info("Start Document Attachment Controller: Fetch attachment by id." );
// fetch the document attachment
DocumentAttachment attachment = documentAttachmentService.getDocumentAttachmentById(attachmentId);
final File file = new File(attachment.getPath() + Constants.FILE_SEPERATOR + attachment.getFileName());
// convert the file to byte array and write it to the output stream
byte[] contentAsBytes = IOUtils.toByteArray(new FileInputStream(file));
String encoding = Constants.UTF8_FORMAT;
response.setCharacterEncoding(encoding);
/** set header */
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
/** write the file */
response.getOutputStream().write(contentAsBytes);
/** return to view */
response.flushBuffer();
}
我正在尝试使用Junit测试转换它。我的单元测试代码发布在下面:
@InjectMocks
DocumentAttachmentController documentAttachmentController;
@Mock
HttpServletResponse response;
@Autowired
DocumentAttachmentService documentAttachmentService;
@Before
public void setUp() throws Exception {
log.debug("initMocks()");
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetAttachmentById() throws IOException {
log.debug("Test getAttachmentById");
Document doc = new Document();
doc.setDocumentId(1);
DocumentAttachment attachment = new DocumentAttachment();
attachment.setFileName("fileName");
attachment.setId(1);
attachment.setOriginalFileName("originFileName");
attachment.setPath("/");
attachment.setDocument(doc);
when(documentAttachmentService.getDocumentAttachmentById(anyInt())).thenReturn(attachment);
documentAttachmentController.getAttachmentById(1, response);
问题是它抛出了java.lang.NullPointerException。 我调试了我的代码,似乎是条件 documentAttachmentService.getDocumentAttachmentById(附件ID) 从应用程序中不占用所有when语句并返回null。我无法理解这是错的。 有任何想法吗? 感谢名单