如何模拟返回文件的方法

时间:2015-11-13 05:24:34

标签: java unit-testing testing mocking mockito

在我的单元测试中,我想模拟一个在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;
    }

1 个答案:

答案 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;
}