How to run code before initializing SpringJUnit4ClassRunner context?

In my application, I initialize the property before running the spring application as follows:

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

(for reference only: it is used for logging log4j2, which must be installed before spring initialization starts).

Now I want to run @IntegrationTest, but use the same logging configuration. Obviously, I cannot use the code above, since the test is JUnitnot performed using SpringApplication.run.

So how can I initialize the code before starting @RunWith(SpringJUnit4ClassRunner.class)?

Note: this BeforeClassdoes not work, as this is done after the spring context start.

+4
source share
2 answers

You can start initialization in a static initializer. The static initializer will be launched after JUnit loads the test class and before JUnit reads any annotations on it.

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

+5
source

I had a slightly different problem. I need to deploy something to my service after loading the Spring context. The solution uses a custom configuration class for the test and starts the deployment in the 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;)

0
source

All Articles