单元测试:在定义模拟行为后调用@PostConstruct

dwj*_*ton 8 java spring unit-testing mockito

我有两节课:

public MyService     
{
    @Autowired
    private MyDao myDao;     

    private List<Items> list; 

    @PostConstruct
    private void init(){
         list = myDao.getItems(); 
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想要参与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>
Run Code Online (Sandbox Code Playgroud)

单元测试:

@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); 
    }

}
Run Code Online (Sandbox Code Playgroud)

这个问题是MyServicebean被创建,并且在定义模拟行为之前调用了它的@PostConstruct bean.

如何在XML中定义模拟行为,或者@PostConstruct在单元测试设置之后延迟?

小智 8

我的项目有同样的要求.我需要使用@PostConstructor设置一个字符串,我不想运行spring上下文,换句话说我想要简单的模拟.我的要求如下:

public class MyService {

@Autowired
private SomeBean bean;

private String status;

@PostConstruct
private void init() {
    status = someBean.getStatus();
} 
Run Code Online (Sandbox Code Playgroud)

}

解:

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);
  }

}
Run Code Online (Sandbox Code Playgroud)


Use*_*F40 4

MyDao 听起来像是外部系统的抽象。一般来说,外部系统不应该在@PostConstruct方法中调用。相反,让您getItems()通过 中的另一种方法进行调用MyService

Mockito 注入将在 Spring 启动后进行,此时模拟不会像您所看到的那样工作。你不能拖延@PostConstruct。为了解决这个问题并使负载自动运行,请MyService执行SmartLifecyclegetItems()调用start().