带有JUnitTests的Spring组件

时间:2014-07-16 09:52:35

标签: spring

我正在使用实现的Spring @Component ApplicationListener<ContextRefreshedEvent>。此组件在tomcat启动时运行,但是当我运行单元测试时,它会再次运行Component。为什么会这样?

这是组件 -

BackGroundServices实施Thread

@Component
public class RunBackgroundServices implements ApplicationListener<ContextRefreshedEvent> {

    private final BackgroundServices backgroundServices;

    private ExecutorService executor;

    @Autowired
    public RunBackgroundServices(BackgroundServices backgroundServices) {
        this.backgroundServices= backgroundServices;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        executor = Executors.newSingleThreadExecutor();
        executor.submit(backgroundServices);
    }

    public void onApplicationEvent(ContextStoppedEvent event) {
        executor.shutdown();
     }
}

1 个答案:

答案 0 :(得分:0)

你可以像那样注释测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfiguration.class}, loader = AnnotationConfigContextLoader.class)
public class MyTest{}

然后在只能初始化所需的那些bean时创建自己的jUnit测试配置

@Configuration
public class TestConfiguration {
  @Bean
  poublic Xxx xxBean(){
  }
}