我有测试和测试类,它在文件名中使用时间。
测试代码:
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 mocking。当我使用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
不支持。
对我有用的解决方法如下。
由于我在测试中只有一个这样的调用,我删除了变量部分simpleDateFormatTimestamp.format(new Date())+“。txt”
现在,如果我在下面做它工作正常。
String outputpath= inboundDir+inboundFilePrefix;
PowerMockito.whenNew(File.class).withArguments(startsWith(outputpath)).thenReturn(outputFileToInboundDir);
startsWith Matcher在org.mockito.Mockito中可用