mat*_*boy 0 java junit unit-testing file
在Java应用程序中,我有一个类的方法,只使用其名称保存文件.
public void doSomething(){
final File file = new File("XXX"+(new Random().next())+".txt");
file.createNewFile();
}
Run Code Online (Sandbox Code Playgroud)
然后,在使用JUnit 4的单元测试中,我运行执行该方法的类,并XXX.txt在项目的根文件夹中看到使用name创建的文件.
@Test
public void doSomethingTest() throws Exception{
//call doSomething();
Path path = //to project folder
Files.delete(path);
}
Run Code Online (Sandbox Code Playgroud)
如何动态获取此路径,以便我可以使用@After方法删除它?
最简单的方法是通过允许代码将基本目录注入创建文件的位置来使代码可测试.
代替
public Foo() {
}
public void doSomething() {
final File file = new File("XXX" + (new Random().next()) + ".txt");
file.createNewFile();
}
Run Code Online (Sandbox Code Playgroud)
使用
private File baseDirectory;
public Foo() {
this(new File("."));
}
public Foo(File baseDirectory) {
this.baseDirectory = baseDirectory;
}
public void doSomething() {
final File file = new File(baseDirectory, "XXX" + (new Random().next()) + ".txt");
file.createNewFile();
}
Run Code Online (Sandbox Code Playgroud)
现在,您的测试可以创建一个临时的空目录,将其传递给构造函数,调用方法,检查文件并在测试后删除它们.
这可能是你想要的功能,因为总是写在当前目录对我来说似乎不是一个好主意.
| 归档时间: |
|
| 查看次数: |
4885 次 |
| 最近记录: |