java 在 JUnit 测试中读取资源文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40710420/
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-11-03 05:26:00  来源:igfitidea点击:

Reading a resource file in JUnit test

javajunit

提问by Anuruddha

I read text file in my unit test and I placed some input text files in resources folder. Following is the directory structure.

我在单元测试中读取了文本文件,并在资源文件夹中放置了一些输入文本文件。以下是目录结构。

  • src -> com -> au -> myapp -> util -> MyFileReader
  • test -> com -> au -> myapp -> util -> MyFileReaderTest
  • test -> com -> au -> myapp -> resources-> input.txt
  • src -> com -> au -> myapp -> util -> MyFileReader
  • 测试 -> com -> au -> myapp -> util -> MyFileReaderTest
  • 测试 -> com -> au -> myapp -> 资源 -> input.txt

Note that src and test are in the same hierarchy.

请注意, src 和 test 在同一层次结构中。

public class MyFileReaderTest
{

  ClassLoader classLoader = getClass().getClassLoader();

  @Test
  public void testReadInputFile() throws Exception
  {
    String file = classLoader.getResource("test/com/au/myapp/resources/input.txt").getFile();
    List<String> result = InputFileReader.getInstance().readFile(file);
    assertEquals("Size of the list should be 2", 2, result.size());
  }
}

Classloader.getResource()returns null. Really appreciate your assistance.

Classloader.getResource()返回空值。非常感谢您的帮助。

回答by JB Nizet

The classloader uses the classpath to load resources. Your classes are, most probably, in the package com.au.myapp.util. Not in the package test.com.au.myapp.util.

类加载器使用类路径加载资源。您的课程很可能在包中com.au.myapp.util。不在包里test.com.au.myapp.util

The directory structure matched the package structure. That means that the directories src and test are both source roots.

目录结构与包结构匹配。这意味着目录 src 和 test 都是源根。

Since your file is in the directory com/au/myapp/resourcesunder a source root, its package is com.au.myapp.resources.

由于您的文件位于com/au/myapp/resources源根目录下的目录中,因此其包为com.au.myapp.resources.

So you need

所以你需要

classLoader.getResource("com/au/fitbits/resources/input.txt");

This is a resource, loaded from the classpath. It might be a file now, because you're in development mode, and classes are loaded directly from the file system. But once in production, they won't be loaded from the file system anymore, but from a jar file. So you can't use file IO to read the content of this resource. So use

这是从类路径加载的资源。它现在可能是一个文件,因为您处于开发模式,并且类是直接从文件系统加载的。但是一旦投入生产,它们将不再从文件系统加载,而是从 jar 文件加载。所以你不能使用文件IO来读取这个资源的内容。所以用

classLoader.getResourceAsStream("com/au/fitbits/resources/input.txt")

and read from this stream.

并从此流中读取。