Since you are not testing FileListService
but a depending class, you can mock it for tests. Make a mock version in a separate test package which is scanned only by test context. Mark it with @Primary
annotation so it takes precedence over production version.
How to disable @PostConstruct in Spring during Test
-
27-11-2021 - |
Question
Within a Spring Component I have a @PostConstruct
statement. Similar to below:
@Singleton
@Component("filelist")
public class FileListService extends BaseService {
private List listOfFiles = new Arrays.list();
//some other functions
@PostConstruct
public void populate () {
for (File f : FileUtils.listFiles(new File(SystemUtils.JAVA_IO_TMPDIR), new String[]{"txt"},true)){
listOfFiles.add(f.getName());
}
}
@Override
public long count() throws DataSourceException {
return listOfFiles.size();
}
// more methods .....
}
During Unit tests I would not like to have the @PostConstruct
function called, is there a way to telling Spring not to do post processing? Or is there a better Annotation for calling a initiation method on a class durning non-testing ?
Solution
OTHER TIPS
Any of:
- Subclass
FileListService
in your test and override the method to do nothing (as mrembisz says, you would need to place the subclass in package scanned only for tests and mark it as@Primary
) - Change
FileListService
so the list of files is injected by Spring (this is a cleaner design anyway), and in your tests, inject an empty list - Just create it with
new FileListService()
and inject the dependencies yourself - Boot up Spring using a different configuration file/class, without using annotation configuration.
Declare a bean to override the existing class and make it Primary.
@Bean
@Primary
public FileListService fileListService() {
return mock(FileListService.class);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow