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
In a single class, it allows to have more than one @PostConstruct annotated method, and also the order of execution is random.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With