Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

service layer testing in spring mvc using easymock

Service Interface:

public List<UserAccount> getUserAccounts();
public List<UserAccount> getUserAccounts(ResultsetOptions resultsetOptions, List<SortOption> sortOptions);

Service Implementation:

public List<UserAccount> getUserAccounts() {
    return getUserAccounts(null, null);
}
public List<UserAccount> getUserAccounts(ResultsetOptions resultsetOptions, List<SortOption> sortOptions) {
    return getUserAccountDAO().getUserAccounts(resultsetOptions, sortOptions);
}

How can I test this using easymock or any other viable testing methodology? sample code will be appreciated. For the easy mock passing objects as parameters very confusing. Some one clearly explain whats the best approach to test the service layer? testing service interface will be considered as unit test or integration test?

like image 692
kneethan Avatar asked Mar 18 '11 16:03

kneethan


1 Answers

Here you go, assuming you are using JUnit 4 with annotations:

import static org.easymock.EasyMock.createStrictMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;

public class UserAccountServiceTest 

     private UserAccountServiceImpl service;
     private UserAccountDAO mockDao;

     /**
     * setUp overrides the default, We will use it to instantiate our required
     * objects so that we get a clean copy for each test.
     */
     @Before
     public void setUp() {
          service = new UserAccountServiceImpl();
          mockDao = createStrictMock(UserAccountDAO.class);
          service.setUserAccountDAO(mockDao);
     }

    /**
     * This method will test the "rosy" scenario of passing a valid
     * arguments and retrieveing the useraccounts.  
     */
     @Test
     public void testGetUserAccounts() {

          // fill in the values that you may want to return as results
          List<UserAccount> results = new User(); 

          /* You may decide to pass the real objects for ResultsetOptions & SortOptions */
          expect(mockDao.getUserAccounts(null, null)
               .andReturn(results);

          replay(mockDao);
          assertNotNull(service.getUserAccounts(null, null));
          verify(mockDao);
     }

}

You might also find this article useful especially if you are using JUnit 3.

Refer this for a quick help on JUnit 4.

Hope that helps.

like image 134
Nilesh Avatar answered Sep 23 '22 14:09

Nilesh