junit rule_使用@Rule在JUnit中测试文件和目录

junit rule

多亏了TemporaryFolder @Rule在JUnit中使用文件和目录进行测试很容易。

在JUnit中,规则( @Rule )可以用作夹具设置和清除方法( org.junit.Beforeorg.junit.Afterorg.junit.BeforeClassorg.junit.AfterClass )的替代或补充,但是它们功能更强大,并且可以更轻松地在项目和类之间共享。

要测试的代码

public void writeTo(String path, String content) throws IOException {
    Path target = Paths.get(path);
    if (Files.exists(target)) {
        throw new IOException("file already exists");
    }
    Files.copy(new ByteArrayInputStream(content.getBytes("UTF8")), target);
}

上面的方法可以将给定的String内容写入不存在的文件。 有两种情况可以测试。

考试

public class FileWriterTest {

    private FileWriter fileWriter = new FileWriter();

    @Rule
    public TemporaryFolder temporaryFolder = new TemporaryFolder();

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void throwsErrorWhenTargetFileExists() throws IOException {
        // arrange
        File output = temporaryFolder.newFile("output.txt");

        thrown.expect(IOException.class);
        thrown.expectMessage("file already exists");

        // act
        fileWriter.writeTo(output.getPath(), "test");
    }

    @Test
    public void writesContentToFile() throws IOException {
        // arrange
        File output = temporaryFolder.newFolder("reports")
                .toPath()
                .resolve("output.txt")
                .toFile();

        // act
        fileWriter.writeTo(output.getPath(), "test");

        // assert
        assertThat(output)
                .hasContent("test")
                .hasExtension("txt")
                .hasParent(resolvePath("reports"));
    }

    private String resolvePath(String folder) {
        return temporaryFolder
                .getRoot().toPath()
                .resolve(folder)
                .toString();
    }
}

TemporaryFolder规则提供了两种方法来管理文件和目录: newFilenewFolder 。 两种方法都会在setup方法中创建的临时文件夹下返回所需的对象。 如果需要临时文件夹本身的路径,则可以使用TemporaryFolder getRoot方法。

无论测试成功与否,在测试完成时将添加到temp文件夹中的所有内容都将自动删除。

这个例子可以在我在GitHub上的unit-testing-demo项目中找到,还有许多其他例子。

翻译自: https://www.javacodegeeks.com/2015/01/testing-with-files-and-directories-in-junit-with-rule.html

junit rule

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值