如何使用Spring Boot将缓冲的读取器注入到以文件读取器为参数的类中? [英] How do I inject a buffered reader into a class with a file reader as its parameter using Spring boot?

查看:77
本文介绍了如何使用Spring Boot将缓冲的读取器注入到以文件读取器为参数的类中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个Spring Boot应用程序,其中方法的下面一行.

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

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

如何将其注入我的代码中,以便可以在单元测试中对其进行模拟?使用guice,我可以使用提供程序.但是如何使用Spring Boot做到这一点呢?任何帮助将不胜感激.

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.

推荐答案

如果要模拟在方法中包含以下行的类.

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

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

创建类的Mock实例并定义模拟行为,例如:

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.

您可以创建一个缓冲读取器的bean并注入:

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

-Dfilename=SOMEPATH

这篇关于如何使用Spring Boot将缓冲的读取器注入到以文件读取器为参数的类中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆