Given a Spring Boot application that does something on start that needs a mock server:
@SpringBootApplication
public class Application implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
System.err.println("should be 2nd: application init (needs the mock server)");
}
public boolean doSomething() {
System.err.println("should be 3rd: test execution");
return true;
}
}
Therefore, the mock server should be initialized beforehand:
@SpringBootTest
@TestInstance(Lifecycle.PER_CLASS)
class ApplicationITest {
@Autowired
MockServer mockServer;
@Autowired
Application underTest;
@BeforeAll
void setUpInfrastructure() {
mockServer.init();
}
@Test
void doSomething() {
assertTrue(underTest.doSomething());
}
}
@Component
class MockServer {
void init() {
System.err.println("should be 1st: mock server init");
}
}
But the application seems to be initialized always first:
should be 2nd: application init (needs the mock server)
should be 1st: mock server init
should be 3rd: test execution
How can I get those to be executed in the intended order?
I tried using Order(Ordered.HIGHEST_PRECEDENCE)
and @AutoConfigureBefore
with no success.
CodePudding user response:
That is not how it works. How would the test be able to call a method on an @Autowired
instance without the application context being started? That simply is not how it works, hence the result you see.
However as you just want to call an method after the object has been constructed mark the method with @PostConstruct
. With this the init
method will be called as soon as the MockServer
instance has been created and got everything injected.