如何在测试期间禁用Spring中的@PostConstruct

9lowa7mx  于 2024-01-05  发布在  Spring
关注(0)|答案(5)|浏览(290)

在Spring组件中,我有一个@PostConstruct语句。类似于下面:

  1. @Singleton
  2. @Component("filelist")
  3. public class FileListService extends BaseService {
  4. private List listOfFiles = new Arrays.list();
  5. //some other functions
  6. @PostConstruct
  7. public void populate () {
  8. for (File f : FileUtils.listFiles(new File(SystemUtils.JAVA_IO_TMPDIR), new String[]{"txt"},true)){
  9. listOfFiles.add(f.getName());
  10. }
  11. }
  12. @Override
  13. public long count() throws DataSourceException {
  14. return listOfFiles.size();
  15. }
  16. // more methods .....
  17. }

字符串
在单元测试期间,我不想调用@PostConstruct函数,有没有办法告诉Spring不要做后处理?或者有没有更好的Annotation在非测试期间调用类的初始化方法?

abithluo

abithluo1#

以下任何一项:
1.子类FileListService在你的测试中,并覆盖该方法不做任何事情(正如mrembisz所说,你需要将子类放在只为测试扫描的包中,并将其标记为@Primary
1.更改FileListService,以便Spring注入文件列表(无论如何,这是一个更干净的设计),并在测试中注入一个空列表
1.只需使用new FileListService()创建它并自己注入依赖项即可
1.使用不同的配置文件/类 Boot Spring,而不使用annotation configuration。

llycmphe

llycmphe2#

因为你不是在测试FileListService,而是一个依赖的类,所以你可以模拟它来进行测试。在一个单独的测试包中制作一个模拟版本,这个测试包只被测试上下文扫描。用@Primary注解标记它,这样它就优先于生产版本。

zrfyljdw

zrfyljdw3#

Declare一个bean以覆盖现有的类并使其成为Primary。

  1. @Bean
  2. @Primary
  3. public FileListService fileListService() {
  4. return mock(FileListService.class);
  5. }

字符串

7eumitmz

7eumitmz4#

检查配置文件如下:

  1. @PostConstruct
  2. public void populate () {
  3. if (!Arrays.asList(this.environment.getActiveProfiles()).contains("test")) {
  4. for (File f : FileUtils.listFiles(new File(SystemUtils.JAVA_IO_TMPDIR), new
  5. String[]{"txt"},true)){
  6. listOfFiles.add(f.getName());
  7. }
  8. }
  9. }

字符串

x8goxv8g

x8goxv8g5#

我建议您创建另一个bean(在本例中为Service),该bean具有完全相同的@PostConstruct方法。
通过这种方式,您可以轻松地模拟新bean,防止@PostConstruct方法被调用。为了使其更清晰,我在SpringBoot中编写了一个简单的概念证明:

1)首先我们定义我们的Service,不带@PostConstruct方法

  1. @Service
  2. @RefreshScope
  3. public class SomeService {
  4. public void doSomethingAfterPostConstruct() throws Exception {
  5. // ...
  6. }
  7. }

字符串

2)然后我们用第一个服务需要的@PostConstruct**方法定义另一个服务

  1. @Service
  2. public class PostConstructService {
  3. @Autowired
  4. SomeService someService;
  5. @PostConstruct
  6. public void doSomething() throws Exception {
  7. someService.doSomethingAfterPostConstruct();
  8. }
  9. }

3)最后我们可以很容易地通过mock它自己的类来mock @PostConstruct方法

  1. /** Test class to extend **/
  2. @AutoConfigureMockMvc
  3. public abstract class AbstractTestConfig {
  4. @MockBean
  5. PostConstructService postConstructServiceMocked;
  6. }


希望这对你有帮助!:)

展开查看全部

相关问题