问题
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