java - 单元测试 : Call @PostConstruct after defining mocked behaviour

标签 java spring unit-testing mockito postconstruct

我有两个类:

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/

相关文章:

java - 当构造函数需要调用可重写方法时保持干燥

java - Spring:自动创建年月属性值?

spring mongodb写入关注值

java - 在单元测试中使用应用程序类作为实用程序

Java:Applet 标准

java - 计算Java HashMap的子集

java - 无法从复合组件中找到匹配的导航案例

java - 一个Spring应用程序可以有多少个BeanFactory?

multithreading - 如何测试跨线程队列?

node.js - 如何为检查响应返回数据的 http 请求编写测试?