dimanche 3 juillet 2016

Unit testing: Call @PostConstruct after defining mocked behaviour

I have two classes:

public MyService     
{
    @Autowired
    private MyDao myDao;     

    private List<Items> list; 

    @PostConstruct
    private void init(){
         list = myDao.getItems(); 
    }
}

Now I'm wanting involve MyService in a unit test, and so I'll mock the behaviour 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>

Unit Test:

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

}

The the problem with this is that the MyService bean is created, and its @PostConstruct bean called before the mocked behaviour is defined.

How can I either define the mocked behaviour in the XML, or delay @PostConstruct until after the unit test setup?

Aucun commentaire:

Enregistrer un commentaire