Testing @Postconstruct with Mockito

Jan Testowy picture Jan Testowy · Sep 25, 2018 · Viewed 15.8k times · Source

Why when I injecting mocks via Mockito my @Postconstruckt method is not calling?

@Service
public class MyService {
    public MyService() {
        System.out.println("CONSTRUKTOR");
    }

    @PostConstruct
    public void init() {
        System.out.println("POST CONSTRUCT");
    }

@RunWith(MockitoJUnitRunner.class)
public class Mockito1 {

    @InjectMocks
    private MyService service;

    @Before
    public void init() {
    }

Output: Only: CONSTRUKTOR

Answer

Vadim Yemelyanov picture Vadim Yemelyanov · Sep 25, 2018

Because PostConstruct is only spring concept. But you can call postConstruct manually.

@Before
public void prepare() {
    MockitoAnnotations.initMocks(this);
    this.service.init(); //your Injected bean
}