我有一个函数可以用来检测某个目录路径是否存在。这是函数:
public boolean isRunningOnSandbox() {
return Files.isDirectory(Paths.get("/mySandbox/cloud/sandbox"));
}
如您所见,它依赖于静态方法 isDirectory。在我的团队中,我们不使用 PowerMock 进行测试。
那么,我该如何测试这个方法呢?我尝试编写如下测试:
@Rule
public TemporaryFolder temporaryFolder;
@Test
public void test() throws IOException {
File parent = new File("/");
temporaryFolder = new TemporaryFolder(parent);
temporaryFolder.create();
File folder = temporaryFolder.newFolder("mySandbox", "cloud", "sandbox");
subject.isRunningOnSandbox();
}
但是,我得到一个错误
ava.io.IOException: Permission denied
因为它不允许我在根目录下创建一个临时文件夹。我猜想有一种更好的方法来测试这段代码,而不是尝试创建一个文件夹。
最佳答案
有很多方法可以做到,其中一种可能像下面的方法。
假设 isRunningOnSandbox
方法在某个类 SomeClass
中,然后以这种方式重构这个类:
public class SomeClass {
public boolean isRunningOnSandbox() {
return Files.isDirectory(Paths.get(getSanboxPath()));
}
protected String getSanboxPath(){
return "/mySandbox/cloud/sandbox";
}
}
然后在您的测试中将另一个您有权访问的目录注入(inject)此类,例如:
public class SomeClassTest {
class SomeClassToTest extends SomeClass{
String folder;
public SomeClassToTest(String folder){
this.folder = folder;
}
@Override
protected String getSanboxPath(){
return folder;
}
}
static String sandboxFolder = "myTestSandobxFolder";
static Path tempDir;
@BeforeClass
public static void createFolder() throws IOException {
tempDir = Files.createTempDirectory(sandboxFolder);
}
@AfterClass
public static void deleteFolder() throws IOException {
Files.delete(tempDir);
}
@Test
public void IsRunningOnSandbox_shouldReturnTrueWhenPathExists() throws IOException {
//given
SomeClass testedObject = new SomeClassToTest(tempDir.toString());
//when
boolean result = testedObject.isRunningOnSandbox();
//then
assertThat(result).isTrue();
}
@Test
public void IsRunningOnSandbox_shouldReturnFalseWhenPathDoesNotExist() throws IOException {
//given
SomeClass testedObject = new SomeClassToTest("/abcdef123");
//when
boolean result = testedObject.isRunningOnSandbox();
//then
assertThat(result).isFalse();
}
}
关于java - 单元测试目录是否存在 - Junit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56839928/