且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该在哪里放置单元测试期间创建的测试数据文件?

更新时间:2023-02-14 17:40:29

您可以选择 target 文件夹,因为 maven clean plugin 会在 mvn clean 被调用.您还应该能够写入 target 目录,所以这应该可以正常工作.

You could choose the target folder, because the maven clean plugin will delete it by default (at least when you didn't change the configuration) when mvn clean is invoked. You also should be able to write to the target directory, so this should work fine.

尽管如此,如果您在项目中使用 JUnit,我建议您使用 TemporaryFolder 类的内置功能.这将在临时目录中创建一个文件夹,并在每个测试用例之后将其删除.请参阅下面的使用示例.

Nonetheless, in case you use JUnit for your project, I would suggest to use the built-in feature of TemporaryFolder class.
This will create a folder in a temporary directory and delete it after every testcase. See usage example below.

import java.io.File;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class TempFolderTest {

    @Rule
    public TemporaryFolder tempFolder = new TemporaryFolder();

    @Test
    public void test() throws IOException {
        File file = tempFolder.newFile();
    }

}

当你真的想使用 target 目录时,你甚至可以把它作为参数提供给构造函数.但总的来说,我认为不需要自己指定测试文件的位置.

When you actually want to use target directory, you can even give this as an argument to the constructor. But in general I see no need to specify the location of the test files yourself.

@Rule
public TemporaryFolder tempFolder = new TemporaryFolder(new File("target"));