Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing @Postconstruct with Mockito

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

like image 745
Jan Testowy Avatar asked Sep 25 '18 16:09

Jan Testowy


People also ask

Can we have multiple PostConstruct?

In a single class, it allows to have more than one @PostConstruct annotated method, and also the order of execution is random.

How can Postconstructs be prevented?

The method SalesDataAggregate is running on startup because of the @PostConstruct annotation. If you want to keep it from running during tests you can create the class containing the post construct in your test folder and add the @primary annotation so it takes precedence over the class in your main project.

Should PostConstruct be public?

The method on which PostConstruct is applied MAY be public, protected, package private or private. The method MUST NOT be static except for the application client. The method MAY be final.

When PostConstruct is called?

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection.


1 Answers

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
}
like image 152
Vadim Yemelyanov Avatar answered Sep 24 '22 19:09

Vadim Yemelyanov