Java 将测试文件放入 JUnit 的简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2597271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:41:14  来源:igfitidea点击:

Easy way to get a test file into JUnit

javaunit-testingjunitjunit4

提问by benstpierre

Can somebody suggest an easy way to get a reference to a file as a String/InputStream/File/etc type object in a junit test class? Obviously I could paste the file (xml in this case) in as a giant String or read it in as a file but is there a shortcut specific to Junit like this?

有人可以建议一种简单的方法来获取对文件的引用作为 junit 测试类中的 String/InputStream/File/etc 类型对象吗?显然,我可以将文件(在这种情况下为 xml)粘贴为一个巨大的字符串或将其作为文件读取,但是是否有这样的特定于 Junit 的快捷方式?

public class MyTestClass{

@Resource(path="something.xml")
File myTestFile;

@Test
public void toSomeTest(){
...
}

}

回答by Ha.

You can try @Ruleannotation. Here is the example from the docs:

你可以试试@Rule注解。这是文档中的示例:

public static class UsesExternalResource {
    Server myServer = new Server();

    @Rule public ExternalResource resource = new ExternalResource() {
        @Override
        protected void before() throws Throwable {
            myServer.connect();
        };

        @Override
        protected void after() {
            myServer.disconnect();
        };
    };

    @Test public void testFoo() {
        new Client().run(myServer);
    }
}

You just need to create FileResourceclass extending ExternalResource.

您只需要创建FileResource类扩展ExternalResource.

Full Example

完整示例

import static org.junit.Assert.*;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;

public class TestSomething
{
    @Rule
    public ResourceFile res = new ResourceFile("/res.txt");

    @Test
    public void test() throws Exception
    {
        assertTrue(res.getContent().length() > 0);
        assertTrue(res.getFile().exists());
    }
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import org.junit.rules.ExternalResource;

public class ResourceFile extends ExternalResource
{
    String res;
    File file = null;
    InputStream stream;

    public ResourceFile(String res)
    {
        this.res = res;
    }

    public File getFile() throws IOException
    {
        if (file == null)
        {
            createFile();
        }
        return file;
    }

    public InputStream getInputStream()
    {
        return stream;
    }

    public InputStream createInputStream()
    {
        return getClass().getResourceAsStream(res);
    }

    public String getContent() throws IOException
    {
        return getContent("utf-8");
    }

    public String getContent(String charSet) throws IOException
    {
        InputStreamReader reader = new InputStreamReader(createInputStream(),
            Charset.forName(charSet));
        char[] tmp = new char[4096];
        StringBuilder b = new StringBuilder();
        try
        {
            while (true)
            {
                int len = reader.read(tmp);
                if (len < 0)
                {
                    break;
                }
                b.append(tmp, 0, len);
            }
            reader.close();
        }
        finally
        {
            reader.close();
        }
        return b.toString();
    }

    @Override
    protected void before() throws Throwable
    {
        super.before();
        stream = getClass().getResourceAsStream(res);
    }

    @Override
    protected void after()
    {
        try
        {
            stream.close();
        }
        catch (IOException e)
        {
            // ignore
        }
        if (file != null)
        {
            file.delete();
        }
        super.after();
    }

    private void createFile() throws IOException
    {
        file = new File(".",res);
        InputStream stream = getClass().getResourceAsStream(res);
        try
        {
            file.createNewFile();
            FileOutputStream ostream = null;
            try
            {
                ostream = new FileOutputStream(file);
                byte[] buffer = new byte[4096];
                while (true)
                {
                    int len = stream.read(buffer);
                    if (len < 0)
                    {
                        break;
                    }
                    ostream.write(buffer, 0, len);
                }
            }
            finally
            {
                if (ostream != null)
                {
                    ostream.close();
                }
            }
        }
        finally
        {
            stream.close();
        }
    }

}

回答by Joey Gibson

I know you said you didn't want to read the file in by hand, but this is pretty easy

我知道你说过你不想手动读取文件,但这很容易

public class FooTest
{
    private BufferedReader in = null;

    @Before
    public void setup()
        throws IOException
    {
        in = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream("/data.txt")));
    }

    @After
    public void teardown()
        throws IOException
    {
        if (in != null)
        {
            in.close();
        }

        in = null;
    }

    @Test
    public void testFoo()
        throws IOException
    {
        String line = in.readLine();

        assertThat(line, notNullValue());
    }
}

All you have to do is ensure the file in question is in the classpath. If you're using Maven, just put the file in src/test/resources and Maven will include it in the classpath when running your tests. If you need to do this sort of thing a lot, you could put the code that opens the file in a superclass and have your tests inherit from that.

您所要做的就是确保有问题的文件在类路径中。如果您使用 Maven,只需将文件放在 src/test/resources 中,Maven 将在运行测试时将其包含在类路径中。如果您需要经常做这类事情,您可以将打开文件的代码放在超类中,并让您的测试从中继承。

回答by slashnick

If you need to actually get a Fileobject, you could do the following:

如果您需要实际获取一个File对象,您可以执行以下操作:

URL url = this.getClass().getResource("/test.wsdl");
File testWsdl = new File(url.getFile());

Which has the benefit of working cross platform, as described in this blog post.

本博客文章所述,具有跨平台工作的好处。

回答by Guido Celada

You can try doing:

你可以尝试这样做:

String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");

回答by gMale

If you want to load a test resource file as a string with just few lines of code and without any extra dependencies, this does the trick:

如果您想将测试资源文件作为字符串加载,只需几行代码并且没有任何额外的依赖项,就可以这样做:

public String loadResourceAsString(String fileName) throws IOException {
    Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(fileName));
    String contents = scanner.useDelimiter("\A").next();
    scanner.close();
    return contents;
}

"\\A" matches the start of input and there's only ever one. So this parses the entire file contents and returns it as a string. Best of all, it doesn't require any 3rd party libraries (like IOUTils).

"\\A" 匹配输入的开头,并且只有一个。所以这会解析整个文件内容并将其作为字符串返回。最重要的是,它不需要任何 3rd 方库(如 IOUTils)。