我有测试和测试类,它在文件名中使用时间。
测试代码:
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”)或不是。
当类和测试在不同的时间执行时,如何删除此测试失败。
由于
答案 0 :(得分:0)
这是一种可能的解决方案。
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
不支持。
答案 1 :(得分:0)
对我有用的解决方法如下。
由于在测试中只有一个这样的调用,因此我删除了变量部分simpleDateFormatTimestamp.format(new Date())+“。txt”
现在,如果我做不到,那就很好了。
String outputpath= inboundDir+inboundFilePrefix;
PowerMockito.whenNew(File.class).withArguments(startsWith(outputpath)).thenReturn(outputFileToInboundDir);
startsWith Matcher在org.mockito.Mockito中可用