Java – unit testing: calling @PostConstruct after defining simulation behavior
•
Java
I have two classes:
public MyService
{
@Autowired
private MyDao myDao;
private List<Items> list;
@postconstruct
private void init(){
list = myDao.getItems();
}
}
Now I want to involve myservice in the unit test, so I will imitate the behavior of mydao
XML:
<bean class = "com.package.MyService">
<bean class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.package.MyDao"/>
</bean>
<util:list id="responseItems" value-type="com.package.Item">
<ref bean="item1"/>
<ref bean="item2"/>
</util:list>
Unit test:
@ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class MyServiceTest{
@Autowired
MyService myService
@Autowired
MyDao myDao;
@Resource
@Qualifier("responseItems")
private List<Item> responseItems;
@Before
public void setupTests() {
reset(myDao);
when(myDao.getItems()).thenReturn(responseItems);
}
}
The problem with this is to create MyService bean, and call its @postconstruct bean. before defining the simulation behavior.
How do I define simulation behavior in XML or defer @ postconstruct after unit test setup?
Solution
My project has the same requirements I need to set a string using @ postconstructor. I don't want to run the spring context, in other words, I want a simple simulation My requirements are as follows:
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);
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
