在我的单元测试中,我想模拟一个在java中返回文件的方法。如何模拟在java中返回文件的方法?代码看起来像是
private File baseDirectory;
private String fileName;
private File file;
public File getFile(String userName, String hostName)
throws VerifyException, IOException {
hostName = "/" + hostName;
userName = "/" + userName;
baseDirectory = new File(hostName, userName);
if (!baseDirectory.exists()) {
baseDirectory.mkdirs();
}
fileName = new SimpleDateFormat("yyyyMMddhhmmssSSS'.txt'").format(new Date());
file = new File(baseDirectory, fileName);
if (!file.exists()) {
file.createNewFile();
}
return file;
}
答案 0 :(得分:0)
既然你提到了Mockito - 这是一个快速测试我想出来的。使用Mockito Annotations完成。
@Mock
FileFetcher fileFetcher;
@InjectMocks
ClassUnderTest classUnderTest;
@Before
public void init(){
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetFile() throws VerifyException, IOException {
//set expectations
Mockito.when(fileFetcher.getFile(Mockito.anyString(), Mockito.anyString())).thenReturn(getTestFile());
//call
classUnderTest.getFileTest();
//verify
Mockito.verify(fileFetcher, Mockito.times(1));
}
private File getTestFile() {
return null;
}