创建用于JUnit 5测试的临时zip文件夹

时间:2019-03-19 19:05:39

标签: java junit5

我必须测试一些直接在zip文件中操作文本文件的类。我曾考虑为JUnit测试创建一个临时zip文件,并编写一些特定的文本文件以查看类的行为。
我只看过如何使用@TempDir创建临时目录,而不是临时zip文件。

我的问题:
是否可以在JUnit 5中创建一个临时zip文件并在其中写入一些文件?

2 个答案:

答案 0 :(得分:1)

我会看一下zip4j库。

  1. 使用所需文件(在测试类中的@Before注释方法中)创建目录
  2. 压缩目录(使用相同的@Before注释方法)
  3. 执行您要测试的代码
  4. 删除zip文件(在测试类的@After注释方法中)

答案 1 :(得分:-1)

看看这个简单的示例,如何创建一个临时文件夹(及其中的文件)以及如何向其中写入一些内容。

public class JUnitExamplesTest{

    private byte[] bytesOfPoem;
    private byte[] bytesOfText;

    // make sure we create temp folder before anything else...
    @Rule
    public TemporaryFolder folder = new TemporaryFolder();
    // zip file
    public File zipFile;

    // now after temp folder has been created deals with creation of a zip file and content within.
    @Before
    public void setUp() throws IOException {
        // some poem
        String poem = "Roses are red, violets are blue...";
        // some message
        String secretMessage = "Life is beautiful.";
        // turn to bytes in order to write them to zip content entries
        bytesOfPoem = poem.getBytes();
        bytesOfText = secretMessage.getBytes();
        // create a zip file zipFile.7z
        zipFile = folder.newFile("zipFile.7z"); 
        // open streams for writing to zip file
        OutputStream out = new FileOutputStream(zipFile);
        ZipOutputStream zipOutputStream = new ZipOutputStream(out);
        // create entry for poem
        ZipEntry poemEntry = new ZipEntry("/poem.txt");
        // set size for poem entry
        poemEntry.setSize(bytesOfPoem.length);
        // stream entry declaration
        zipOutputStream.putNextEntry(poemEntry);
        // and content within
        zipOutputStream.write(bytesOfPoem);
        ZipEntry messageEntry = new ZipEntry("/Directory/text.txt");
        messageEntry.setSize(bytesOfText.length);
        zipOutputStream.putNextEntry(messageEntry);
        zipOutputStream.write(bytesOfText);
        zipOutputStream.close();
    }
}