gpt4 book ai didi

java - 使用 Junit 和 mockito 测试 catch block 逻辑

转载 作者:行者123 更新时间:2023-11-30 02:29:35 25 4
gpt4 key购买 nike

我有类要测试,如下所示:

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 block 中的逻辑?

最佳答案

如果 sendEmailToSupport 至少是一个包级别的方法,那么您可以采用如下方法:

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();
}
}

关于java - 使用 Junit 和 mockito 测试 catch block 逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44569595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com