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.
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.