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

9lowa7mx  于 5个月前  发布在  Spring
关注(0)|答案(5)|浏览(104)

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

@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 .....
}

字符串
在单元测试期间,我不想调用@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。

@Bean
@Primary
public FileListService fileListService() {
 return mock(FileListService.class);
}

字符串

7eumitmz

7eumitmz4#

检查配置文件如下:

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

        }           
    }

字符串

x8goxv8g

x8goxv8g5#

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

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

@Service
@RefreshScope
public class SomeService {
 
    public void doSomethingAfterPostConstruct() throws Exception  {
        // ...
    }

}

字符串

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

@Service
public class PostConstructService {

    @Autowired
    SomeService someService;

    @PostConstruct
    public void doSomething() throws Exception {
        someService.doSomethingAfterPostConstruct();
    }
}

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

/** Test class to extend **/
@AutoConfigureMockMvc
public abstract class AbstractTestConfig {

    @MockBean
    PostConstructService postConstructServiceMocked;

}


希望这对你有帮助!:)

相关问题