【问题标题】:NIO load file in an unit test from src/test/resourcesNIO 在 src/test/resources 的单元测试中加载文件
【发布时间】:2013-09-04 15:18:23
【问题描述】:

问题

我想用 java7s NIO 在 java 中编写一个数据导入。用户以字符串形式输入文件的路径,程序尝试使用路径打开它。当它想读取它的 DosFileAttributes 时,会发生 java.nio.file.NoSuchFileException: file.txt。

我发现了什么

到目前为止,我发现的唯一答案是使用资源流 - 但这不切实际,因为要加载的文件是由用户提供的,不应该是 jar 的一部分。还是我误会了? http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29

我有什么

设置:

  • Maven 3
  • Java7
  • 测试NG
  • 弹簧

项目结构:

  • src/main/java - 类
  • src/test/java - 测试用例
  • src/test/resources - 也许是 file.txt ?实际上它在那里

加载文件的源:

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.DosFileAttributes;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

@Component( "fileLoader" )
public class BufferdFileLoader
        implements FileLoader {

    @Override
    public List<String> loadFile( String path )
            throws IOException {

        if ( path == null || path.length() == 0 ) {
            throw new IllegalArgumentException( "path should not be null" );
        }

        Path file = Paths.get( path );

        // here the Exception is thrown
        DosFileAttributes attrs = Files.readAttributes( file, DosFileAttributes.class );

        if ( !attrs.isRegularFile() ) {
            throw new IOException( "could not read file, invalid path" );
        }

        List<String> result = new ArrayList<String>();

        try (BufferedReader reader = Files.newBufferedReader( file, Charset.forName( "UTF-8" ) )) {
            String line = null;
            while ( ( line = reader.readLine() ) != null ) {
                result.add( line );
            }
        }

        return result;
    }
}

测试用例也很简单:

import java.io.IOException;
import java.util.List;

import javax.inject.Inject;

import lombok.Setter;

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * Class under test {@link BufferdFileLoader}
 * 
 */
@ContextConfiguration
public class BufferdFileLoaderTest
        extends AbstractTestNGSpringContextTests {

    /**
     * Class under test
     */
    @Inject
    @Setter
    private BufferdFileLoader bufferdFileLoader;


    /**
     * Method under test {@link BufferdFileLoader#loadFile(String)}
     * 
     * @throws IOException
     */
    @Test( groups = { "integration" }, enabled = true )
    public void testImportFeedsFromXMLFileWitEmptyXml()
            throws IOException {

        String filename = "empty-example-takeout.xml";

        List<String> list = this.bufferdFileLoader.loadFile( filename );

        Assert.assertEquals( list.size(), 0 );

    }

}

所以我的问题是

如何使用 NIO 加载文件,以便它可以在 maven 中测试并且也可以在生产环境中工作?

【问题讨论】:

    标签: java spring maven junit nio


    【解决方案1】:

    嗯,问题是在测试的类路径中为您的测试资源获取正确的Path

    编辑:这样更简洁:

    Paths.get(getClass().getResource("/"+filename).toURI()).toString()
    

    【讨论】:

    • 我明白你的意思,现在测试工作正常。但我也希望它在 jar 中运行。 java -jar app f:\myfile.txt 不会与上面提到的 .getResource 一起运行
    • @Thomas :我的答案中的 sn-p 应该替换您的测试方法中的相关代码。您不应该应用对 loadFile 方法的更改 - 它应该保持原样。 sn -p 只是提供了与您的测试文件的路径分类器相对应的字符串,以便它可以正确地转换回loadFile 中的Path
    【解决方案2】:

    如果您创建一个名为 testing 的文件夹,您可以使用以下内容:

    Paths.get(getClass().getResource("/testing").toURI()).resolve(filename)
    

    如果文件不存在,其他方法会抛出空指针异常

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-22
      • 2016-11-11
      • 2011-02-05
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 2021-09-15
      相关资源
      最近更新 更多