我有一个有趣的场景,我需要在File
我的 POJO 中注入一个引用(这样,在我的测试类中,我可以存根File
而不实际将任何内容写入磁盘),但文件的名称实际上是不知道的,直到运行:
public class MyPOJO {
private File file;
private FileWriter writer;
// Getter and setter for file & writer
public void writeToDisk(String message) {
String fileName = complexLogicToBuildFileName();
// How do I do the equivalent of: file.setName(fileName);
try {
writer.write(message);
writer.close();
} catch(IOException ioe) {
...
}
}
}
public class MyPOJOTest {
@Test
public void verifyWriteToDiskAttemptsToWrite() {
MyPOJO pojo = new MyPOJO();
File mockFile = Mockito.mock(File.class);
FileWriter mockWriter = Mockito.mock(FileWriter.class);
Mockito.doNothing().when(mockWriter).write(Mockito.anyString());
pojo.setWriter(mockWriter);
pojo.setFile(mockFile);
pojo.writeToDisk("This won't write to disk.");
Mockito.verify(mockWriter).write("This won't write to disk.");
}
}
问题是,由于强制构造函数,在我有机会执行之前File(String)
,我必须将注入File
的实例绑定到文件名,而这不能用简单的 setter 方法覆盖。关于如何保存和注入属性的任何想法(为了可测试性),但仍然让我用来命名文件?提前致谢。complexLogicToBuildFileName()
file
fileWriter
complexLogicToBuildFileName()