单元测试:在定义模拟行为后调用@PostConstruct
2022-09-03 05:27:48
我有两个类:
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);
}
}
这样做的问题是,在定义模拟行为之前,它@PostConstruct bean被创造出来。MyService
如何在 XML 中定义模拟行为或延迟到单元测试设置之后?@PostConstruct