NullPointer在单元测试期间负责从文件中检索数据的方法

时间:2019-04-17 20:42:12

标签: java file unit-testing

我正在尝试对负责从文本文件中检索数据的方法进行单元测试。

具有该方法的类的外观如下:

package contentfile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ContentFileRetrieverService implements ContentFileRetriever {

    @Override
    public String[] getContentFile(String pathName) {

        Stream<String> contentFileStream;
        try {
            contentFileStream = Files.lines(Paths.get(pathName));
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }

        return contentFileStream.toArray(String[]::new);
    }
}

这是测试的样子:

package contentfile;

import org.junit.Rule;
import org.junit.jupiter.api.Test;

import static org.junit.Assert.*;

class ContentFileRetrieverServiceTest {

    private ContentFileRetrieverService contentFileRetrieverService;

//    @Rule
//    TemporaryFiles temporaryFiles = new TemporaryFiles();

    @Test
    void getContentFile() {
        String pathFile = "tekst.txt";
        String[] testedContent = contentFileRetrieverService.getContentFile(pathFile);
        String[] expected = {"la", "la"};
        assertArrayEquals(expected, testedContent);
    }
}

不幸的是,我在调用getContentFile方法时得到了NullPointer。 这是stacktrace:

java.lang.NullPointerException
    at contentfile.ContentFileRetrieverServiceTest.getContentFile(ContentFileRetrieverServiceTest.java:18)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

内容文件

Line1 a
Line2 b c
Line 3

1 个答案:

答案 0 :(得分:5)

(array([1, 2, 3]), array([2.1, 0.8, 0.2])) 为null,因此是例外。

您需要在测试之前实例化它:

private ContentFileRetrieverService contentFileRetrieverService;