我有一个函数,用于检测特定目录路径是否存在。功能如下:

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";
    }
}

然后在测试中将您有权访问的另一个目录注入到此类中,例如:
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/

10-14 09:00
查看更多