我有两节课:
public MyService
{
@Autowired
private MyDao myDao;
private List<Items> list;
@PostConstruct
private void init(){
list = myDao.getItems();
}
}
现在我想在单元测试中涉及MyService,所以我会模仿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>
单元测试:
@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);
}
}
这样做的问题是创建了MyService bean,并且在定义模拟行为之前调用了它的@PostConstruct bean.
如何在XML中定义模拟行为,或者在单元测试设置之后延迟@PostConstruct?
解决方法:
我的项目有同样的要求.我需要使用@PostConstructor设置一个字符串,我不想运行spring上下文,换句话说我想要简单的模拟.我的要求如下:
public class MyService {
@Autowired
private SomeBean bean;
private String status;
@PostConstruct
private void init() {
status = someBean.getStatus();
}
}
解:
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);
}
}