繁体   English   中英

如何在SpringJUnit4ClassRunner上下文初始化之前运行代码?

[英]How to run code before SpringJUnit4ClassRunner context initialization?

在我的应用程序中,我在spring应用程序启动之前初始化属性,如下所示

MapLookup.setMainArguments(new String[] {"logging.profile", profile}); //from args
SpringApplication.run(source, args);

(仅供参考:它用于log4j2 ,必须在spring开始初始化之前设置)。

现在我想运行@IntegrationTest ,但使用相同的日志配置。 显然我不能使用上面的代码,因为没有使用SpringApplication.run执行JUnit测试。

那么,如何在@RunWith(SpringJUnit4ClassRunner.class)启动之前初始化代码呢?

注意: BeforeClass不起作用,因为它在spring上下文启动后执行。

您可以在静态初始化程序中运行初始化。 静态初始化程序将在JUnit加载测试类之后和JUnit读取其上的任何注释之前运行。

或者,您可以首先使用您自己的Runner初始化SpringJUnit4ClassRunner,然后运行SpringJUnit4ClassRunner

我有一个稍微不同的问题。 加载Spring上下文后,我需要在服务中部署一些东西。 解决方案使用自定义配置类进行测试,并在@PostConstruct方法中运行部署。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class, loader = AnnotationConfigContextLoader.class)
public class JunitTest {

  @Configuration
  @ComponentScan(basePackages = { "de.foo })
  public static class TestMConfig {

      @Autowired
      private DeploymentService service;


      @PostConstruct
      public void init() {
        service.deploy(...);
      }
  }

  @Test
  public void test() {
      ...
  }
}

也许这有帮助,有人,某个时候,某个地方;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM