简体   繁体   English

从src / test / resources进行单元测试中的NIO加载文件

[英]NIO load file in an unit test from src/test/resources

The Problem 问题

I'd like to write a data import in java with java7s NIO. 我想用Java7s NIO在java中编写数据导入。 The user enters the path of a file as a String and the programm try to open it by using Paths. 用户以String形式输入文件的路径,程序尝试使用Paths打开它。 When it want to read its DosFileAttributes an java.nio.file.NoSuchFileException: file.txt occures. 当它想要读取它的DosFileAttributes时,会发生java.nio.file.NoSuchFileException:file.txt。

What i've found 我发现了什么

The only answers i've found till yet is to use an resource Stream - but this seams not practicable, because the file to be loaded is provided by the user and should not be part of the jar. 我发现的唯一答案是使用资源Stream - 但这种接缝不实用,因为要加载的文件是由用户提供的,不应该是jar的一部分。 Or did i missunderstood it? 还是我错过了理解? http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29 http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29

What i've got 我得到了什么

The Setup: 设置:

  • Maven 3 Maven 3
  • Java7 Java7
  • TestNG TestNG的
  • Spring 弹簧

Project Structure: 项目结构:

  • src/main/java - the classes src / main / java - 类
  • src/test/java - the testcases src / test / java - 测试用例
  • src/test/resources - perhaps file.txt ? src / test / resources - 也许是file.txt? actual it is there 实际上它就在那里

The source that loads the file: 加载文件的源:

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

And the Test case is as simple: 测试案例很简单:

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

    }

}

So my question is 所以我的问题是

How to load a file using NIO so it is testable with maven and also works in production environment? 如何使用NIO加载文件,以便可以使用maven测试,也可以在生产环境中使用?

Well, it's a matter of obtaining the correct Path for you test resource in the classpath in your test. 好吧,这是在测试中的类Path为测试资源获取正确Path的问题。

EDIT: this is more concise: 编辑:这更简洁:

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

If you create a folder named testing you can use the following: 如果创建名为testing的文件夹,则可以使用以下命令:

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

The other method will throw a null pointer exception if the file does not exists 如果文件不存在,另一个方法将抛出空指针异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM