我需要在JUnit中介绍XMLStreamException,但我不知道如何触发此异常。 这是我班上的代码片段
try {
writer.add(factory.createStartElement("", "", BatchConstants.HEADER));
writer.add(factory.createStartElement("", "", BatchConstants.MESSAGE_TYPE));
writer.add(factory.createCharacters(BatchConstants.LPR_ENTITY));
writer.add(factory.createEndElement("", "", BatchConstants.MESSAGE_TYPE));
writer.add(factory.createStartElement("", "", BatchConstants.SEND_DATETIME));
writer.add(factory.createCharacters(batchProcessControlEntity.getCreatedDt().toString()));
writer.add(factory.createEndElement("", "", BatchConstants.SEND_DATETIME));
writer.add(factory.createEndElement("", "", BatchConstants.HEADER));
} catch (XMLStreamException e) {
this.logger.logError(e.getMessage(), e);
}
我可以使用此内容覆盖上述代码段的测试
@Test
public void testWrite() throws IOException, XMLStreamException {
BatchProcessControlEntity batchProcessControlEntity = new BatchProcessControlEntity();
batchProcessControlEntity.setCreatedDt(new Date());
Mockito.when(this.batchProcessControlJpaRepository.findByBatchProcessCtrlId(Matchers.anyObject()))
.thenReturn(batchProcessControlEntity);
XMLEventWriter eventWriter = Mockito.mock(XMLEventWriter.class);
this.headerWriter.write(eventWriter);
}
但是我不知道触发XMLStreamException需要什么输入。 谢谢你。
答案 0 :(得分:1)
您使用了模仿的doThrow方法。
一些有趣的示例代码:
XMLEventWriter eventWriter = Mockito.mock(XMLEventWriter.class);
doThrow(new XMLStreamException("This is my exception"))
.when(eventWriter)
.add(any(XMLEvent.class));