使用Junit和Mockito测试catch块逻辑

使用Junit和Mockito测试catch块逻辑

本文介绍了使用Junit和Mockito测试catch块逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有要测试的课程,如下所示:

I have class to test like below:

public class ReportWriter {
    private FileWrter fw;
    private static Logger logger = Logger.getLogger(ReportWriter.class);
    public ReportWriter(FileWrter fw) {
        this.fw = fw;
    }
    public void writeData(Data) {
        try{
            fw.open();
            fw.write(data);
            fw.close();
        } **catch(DiskFullException e) {
            //after catch we log and handle it without rethrow the exception
            logger.log(Level.WARN, "warning log here", e);
            // some more logic here
            sendEmailToSupport();
        }**
    }
}

问题是如何在catch块中测试逻辑?

The question is how to test the logic in catch block?

推荐答案

如果sendEmailToSupport至少是包级方法,则可以使用以下方法:

If the sendEmailToSupport is at least a package level method, then you could go for something like:

public class ReportWriterClass{

   @Spy
   @InjectMocks
   private ReportWriter reportWriterSpy;

   @Mock
   private FileWrter fwMock;

   @Before
   public void init(){
       MockitoAnnotations.initMocks(this);
   }

   @Test
   public void shouldSendEmail_whenDiskIsFull() throws Exception{
       // Arrange
       Data data = new Data();

       doNothing().when(reportWriterSpy).sendEmailToSupport());
       doThrow(new DiskFullException()).when(fwMock).write(data);

       // Act
       reportWriterSpy.writeData(data);

      // Assert
      verify(reportWriterSpy).sendEmailToSupport();
   }
}

这篇关于使用Junit和Mockito测试catch块逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 21:07