12

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.

2 Answers 2

14

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

Sign up to request clarification or add additional context in comments.

9 Comments

You mean a static { } block in the test class? I just tried it, but without success.
I tried it too, it clearly runs before SpringJUnit4ClassRunner, JUnit cannot know about SpringJUnit4ClassRunner before it loads the test class and once it loads the class it will run static {}
Hm, ok it runs before the ClassRunner, but in runs after log4j initialization... So I issume this is actually a log4j issue indeed?
log4j initialization runs only if some code uses it, possibly somewhere some code did it before you run the test
I also tried moving the static block to an extended SpringJUnit4ClassRunner, but got the same result. It is strange that log4j actually runs before the ClassRunner, because when running from static void main the log4j config is first initialized on SpringApplication.run.
|
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.