I want to mock a method call inside @PostConstruct
.
During normal application start, this initializes some data from a database.
But during a test or integration test, I want to mock that database call and return my mocked Set<String>
instead.
Problem: @PostConstruct
is always called before the mock is set up in @Before
method:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MockITest {
@MockBean
private DatabaseService db;
@Autowird
private MyService service; //the service to test
@Before
public void setup() {
given(db.findAllByName()).willReturn(Set.of("john", "doe"));
}
@Test
public void testServiceInPostConstructIsMocked() {
service.run();
}
}
public class MyService {
@Autowired
private DatabaseService db;
private Set<String> names;
//initialization on startup, and cache the results in the member field
@PostConstruct
public void init() {
names = db.findAllByName();
}
public void run() {
System.out.println(names); //always empty for the test
}
}
How can I still mock the database service properly?