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


77

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

public class MyTestClass{

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

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

}

Answers:


85

您可以尝试@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);
    }
}

您只需要创建FileResource扩展类即可ExternalResource

完整的例子

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();
        }
    }

}


9
哇。到目前为止,这似乎是我最好的答案。我真的很难预测未来。
哈。

77

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

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

其中有工作的跨平台,如中所描述的好处这个博客帖子


14

我知道您说过您不想手工阅读文件,但这很容易

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());
    }
}

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


感谢您实际说的是文件的位置,不仅是如何打开它!
文斯


1

如果要以仅几行代码且没有任何其他依赖项的形式将测试资源文件加载为字符串,则可以做到这一点:

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”匹配输入的开始,并且只有一个。因此,它将解析整个文件内容,并将其作为字符串返回。最棒的是,它不需要任何第三方库(例如IOUTils)。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.