How do I inject a buffered reader into a class with a file reader as its parameter using Spring boot?

早过忘川 提交于 2020-01-07 03:25:09

问题


I have this spring boot application in which I have the below line inside a method.

BufferedReader reader = new BufferedReader(new FileReader("somePath"));

How can I inject this into my code so I can mock it for my unit tests? Using guice I could use a provider. But how can I achieve this using spring boot? Any help would be much appreciated.


回答1:


If you want to mock the class which have the below line inside a method.

BufferedReader reader = new BufferedReader(new FileReader("somePath"));

Create a Mock instance of the class and define the mock behaviour like :

@MockBean
private TestClass testClass;

when(testClass.readFile()).thenReturn(content);

where content is the output you want to return.

you can create a bean of buffered reader and inject :

    @Bean
BufferedReader reader(@Value("${filename}") String fileName) throws FileNotFoundException{

    return new BufferedReader(new FileReader(fileName));
}

-Dfilename=SOMEPATH




回答2:


You can create a bean like below.

    @Bean
    public BufferedReader bufferedReader() throws FileNotFoundException {
        return new BufferedReader(new FileReader("somePath"));
    }

Now you can inject it in your class.

    @Inject
    private BufferedReader bufferedReader;

To take filename from properties, create a foo.properties file inside resources directory And then do this:

@Configuration
@PropertySource("classpath:foo.properties")
public class SampleConfig {
    @Value("${fileName}")
    private String fileName;

    @Bean
    public BufferedReader bufferedReader() throws FileNotFoundException {
        return new BufferedReader(new FileReader(fileName));
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

Foo.properties:

fileName=file_name


来源:https://stackoverflow.com/questions/42171280/how-do-i-inject-a-buffered-reader-into-a-class-with-a-file-reader-as-its-paramet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!