We are using Spring-boot 2.3.5. One of our classes uses a @PostConstruct annotation and this is causing me a lot of problems in testing. It seems to me that the order of events is
- create all Mocks
- start application
- call @Before-methods
- start test
(As pointed out in this answer to largely the same question )
My issue is that I have a lot of beans mocked but the the @PostConstruct method is called before the mocks are configured in any @Before methods.
So I have
Service {
@AutoWired
componentOne
@AutoWired
componentTwo
@AutoWired
componentThree
…
@PostConstruct
public void doSomeWork() throws InvocationTargetException, IllegalAccessException {
…
}
And Test Class
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(locations = "classpath:application.yml")
@ActiveProfiles("development")
public abstract class AbstractTests {
@LocalServerPort
private int port;
@Value("${server.servlet.context-path}")
String contextPath;
protected final Faker faker = new Faker(Locale.forLanguageTag("en-GB"));
@Autowired
protected SettingsService settingsService;
@MockBean
private ServiceOne accountingImportService;
@MockBean
private ServiceTwo accountingImportService;
@MockBean
private ServiceThree accountingImportService;
@BeforeEach
public void setup() throws Exception {
… configure mocks
The @PostConstruct fires before the mocks are configured and fails.
I have tried (from the linked question)
@MockBean(answer = CALLS_REAL_METHODS)
protected SsoService ssoService;
Which doesn’t seem to help at all
and
@TestConfiguration
public static class EarlyConfiguration {
@Bean
@Primary
public Service mockService() {
Service service = mock(Service.class);
when(service.getLocalTimeZone()).thenReturn(ZoneId.systemDefault());
return service;
}
}
@Autowired
protected Service service;
And this fails on the auto wire because it can’t configure the class with its autowired (mocked) dependencies.
Is there a simple way to configure a when in a static context as the mockBean is declared ?