简体   繁体   English

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

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

In my application I initialize a property before spring application startup as follows: 在我的应用程序中,我在spring应用程序启动之前初始化属性,如下所示

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

(just for reference: it is used for log4j2 logging, which must be set before spring starts to initialize). (仅供参考:它用于log4j2 ,必须在spring开始初始化之前设置)。

Now I want to run an @IntegrationTest , but use the same logging configuration. 现在我想运行@IntegrationTest ,但使用相同的日志配置。 Obviously I cannot use the code above, as a JUnit test is not executed using SpringApplication.run . 显然我不能使用上面的代码,因为没有使用SpringApplication.run执行JUnit测试。

So, how could I initialize code before a @RunWith(SpringJUnit4ClassRunner.class) starts? 那么,如何在@RunWith(SpringJUnit4ClassRunner.class)启动之前初始化代码呢?

Note: BeforeClass does not work as this is executed after spring context startup. 注意: BeforeClass不起作用,因为它在spring上下文启动后执行。

You can run the initialization in a static initializer. 您可以在静态初始化程序中运行初始化。 Static initializer will run after JUnit loads the test class and before JUnit reads any annotations on it. 静态初始化程序将在JUnit加载测试类之后和JUnit读取其上的任何注释之前运行。

Alternatively you can extend SpringJUnit4ClassRunner with your own Runner initialize in it first and then run SpringJUnit4ClassRunner 或者,您可以首先使用您自己的Runner初始化SpringJUnit4ClassRunner,然后运行SpringJUnit4ClassRunner

I had a slightly different problem. 我有一个稍微不同的问题。 I need to deploy something to my service after the Spring context is loaded. 加载Spring上下文后,我需要在服务中部署一些东西。 Solution use a custom config class for the test and run the deployment within a @PostConstruct Method. 解决方案使用自定义配置类进行测试,并在@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() {
      ...
  }
}

Maybe this helps, someone, sometime, somewhere ;) 也许这有帮助,有人,某个时候,某个地方;)

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

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