将测试文件导入 JUnit 的简单方法
有人可以建议一种简单的方法来获取对文件的引用作为 junit 测试类中的 String/InputStream/File/etc 类型对象吗?显然我可以将文件(在本例中为 xml)作为一个巨大的字符串粘贴或将其作为文件读取,但是是否有像这样的特定于 Junit 的快捷方式?
public class MyTestClass{
@Resource(path="something.xml")
File myTestFile;
@Test
public void toSomeTest(){
...
}
}
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?
public class MyTestClass{
@Resource(path="something.xml")
File myTestFile;
@Test
public void toSomeTest(){
...
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以尝试
@Rule
注解。以下是文档中的示例:您只需创建扩展
ExternalResource
的FileResource
类。完整示例
You can try
@Rule
annotation. Here is the example from the docs:You just need to create
FileResource
class extendingExternalResource
.Full Example
如果您需要实际获取一个 File 对象,您可以执行以下操作:
这具有跨平台工作的优点,如 这篇博文。
If you need to actually get a
File
object, you could do the following:Which has the benefit of working cross platform, as described in this blog post.
我知道您说过您不想手动读取文件,但这非常简单,
您所要做的就是确保有问题的文件位于类路径中。如果您使用 Maven,只需将该文件放入 src/test/resources 中,Maven 就会在运行测试时将其包含在类路径中。如果您需要经常做这种事情,您可以将打开文件的代码放在超类中,并让您的测试继承它。
I know you said you didn't want to read the file in by hand, but this is pretty easy
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.
如果您想将测试资源文件作为字符串加载,只需几行代码并且没有任何额外的依赖项,那么这可以解决问题:
“\\A”匹配输入的开头,并且只有一个。因此,这会解析整个文件内容并将其作为字符串返回。最重要的是,它不需要任何第三方库(如 IOUTils)。
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:
"\\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).
你可以尝试这样做:
You can try doing: