ContentFileRetrieverService

ContentFileRetrieverService

This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                去年关闭。
            
        

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

使用该方法的类如下所示:

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

最佳答案

private ContentFileRetrieverService contentFileRetrieverService;为null,因此是例外。

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

private ContentFileRetrieverService contentFileRetrieverService = new ContentFileRetrieverService();

07-27 13:46