I have two classes:
public MyService {
@Autowired
private MyDao myDao;
private List list;
@PostConstruct
private void
I have same kind of requirement in my project. where i need to set a string using @PostConstructor and I did not want to ran spring context or in other words I want simple mock. My requirement was follow:
public class MyService {
@Autowired
private SomeBean bean;
private String status;
@PostConstruct
private void init() {
status = someBean.getStatus();
}
}
Solution:
public class MyServiceTest(){
@InjectMocks
private MyService target;
@Mock
private SomeBean mockBean;
@Before
public void setUp() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
MockitoAnnotations.initMocks(this);
when(mockBean.getStatus()).thenReturn("http://test");
//call post-constructor
Method postConstruct = MyService.class.getDeclaredMethod("init",null); // methodName,parameters
postConstruct.setAccessible(true);
postConstruct.invoke(target);
}
}
MyDao sounds like it is an abstraction of an external system. Generally external systems shouldn't be called in @PostConstruct
methods. Instead have your getItems()
called by another method in MyService
.
Mockito injections will take place after the Spring initiation at which point the mock isn't working as you see. You cannot delay the @PostConstruct
. To beat this and have the load run automatically have MyService
implement SmartLifecycle
and call getItems()
in start()
.