我有两个类:
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);
}
}
关于java - 单元测试 : Call @PostConstruct after defining mocked behaviour,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38175822/