简体   繁体   中英

Testing service layer without DAO

Can you give me an example of how I test my service layer without the DAO using mock objects, Spring or any other framework. My Java code looks like this:

public int myServiceMethod(int number) {

    int myInt = Factory.getDAOImpl.getNumber();
    return myInt + number * 8;
}

I want to test the logic of myServiceMethod but without testing the DAO method. Is it possible? Do I have to refactor it? Can you show me an example of how to test this simple method. Thank you

In your example, you would just need to mock your DAO (for example using Mockito ), and fix a number to be returned.

DAOImpl myDao = mock(DAOImpl.class);
when(myDao.getNumber()).thenReturn(7);

When calling the method getNumber , you'll always get 7. Pass this DAO when creating your service, and write your test as normal:

assertEquals(224, service.myServiceMethod(4));

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM