我有测试和被测类,它在文件名中使用时间。
测试代码:
SimpleDateFormat simpleDateFormatTimestamp = new SimpleDateFormat("yyMMddHHmmss");
String outputpath= inboundDir+inboundFilePrefix+simpleDateFormatTimestamp.format(new Date())+".txt";
PowerMockito.whenNew(File.class).withArguments(outputpath).thenReturn(outputFileToInboundDir);
被测类代码:
File outputFile=new File(inboundDir+inboundFilePrefix+simpleDateFormatTimestamp.format(new Date())+".txt");
同样在测试和被测类中,我还有其他新文件调用,因此我无法使用withAnyArguments模拟。当我与withAnyArguments一起使用时,所有新文件调用仅返回一个模拟。
我的测试用例有时会通过,而有时会失败,这取决于测试和被测类是否在同一秒内运行(“ yyMMddHHmmss”)。
当类和测试在不同的秒执行时,如何消除此测试失败。
谢谢
最佳答案
这是一种可能的解决方案。
String outputpath= inboundDir+inboundFilePrefix+simpleDateFormatTimestamp.format(new Date())+".txt";
PowerMockito.whenNew(File.class).withAnyArguments().thenAnswer(invocation -> {
String firstArgument = (String) invocation.getArguments()[0];
// do a pattern matching for firstArgument with a regex containing date in it.
// if its true then return outputpath
// else return something else
});
我们本可以使用ArgumentCaptor,但是
PowerMockito.whenNew
不支持。