我应该在哪里放置单元测试期间创建的测试数据文件? [英] Where should I place test data files created during unit test?

查看:78
本文介绍了我应该在哪里放置单元测试期间创建的测试数据文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为单元测试的一部分,在我的 maven java 项目中,我必须创建一些文件.虽然我每次测试后都会清理,但为了安全起见,我想将它们放在应该在我的项目中的文件夹中.如果目标"文件夹是正确的选择,你能建议我吗?

As a part of unit test, in my maven java project, I have to create some files. Although I clean up after every test but still to be at safer side, I want to place them in folder which should be in my project. Can you suggest me if 'target' folder is the right choice?

我可以将它们放在项目之外,但要使其在所有机器上都可以轻松执行,这将是乏味的.此外,我可能会在不受团队直接控制的机器上出现文件或目录权限问题.

I can place them outside in a project but then to make it easily executable in all machines this will be tedious. Also, I might file or directory permissions issue in machines not directly controlled by my team.

推荐答案

您可以选择 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 类的内置功能.<​​br>这将在临时目录中创建一个文件夹,并在每个测试用例之后将其删除.请参阅下面的使用示例.

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

这篇关于我应该在哪里放置单元测试期间创建的测试数据文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆