简体   繁体   中英

How to run code before SpringJUnit4ClassRunner context initialization?

In my application I initialize a property before spring application startup as follows:

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).

Now I want to run an @IntegrationTest , but use the same logging configuration. Obviously I cannot use the code above, as a JUnit test is not executed using SpringApplication.run .

So, how could I initialize code before a @RunWith(SpringJUnit4ClassRunner.class) starts?

Note: BeforeClass does not work as this is executed after spring context startup.

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.

Alternatively you can extend SpringJUnit4ClassRunner with your own Runner initialize in it first and then run SpringJUnit4ClassRunner

I had a slightly different problem. I need to deploy something to my service after the Spring context is loaded. Solution use a custom config class for the test and run the deployment within a @PostConstruct Method.

@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 ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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