使用easymock在spring mvc中进行服务层测试

时间:2011-03-18 16:23:00

标签: unit-testing junit easymock

服务接口:

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

服务实施:

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

如何使用easymock或任何其他可行的测试方法对此进行测试?示例代码将不胜感激。对于简单的模拟传递对象作为参数非常混乱。有人清楚地解释了测试服务层的最佳方法是什么?测试服务接口会被视为单元测试还是集成测试?

1 个答案:

答案 0 :(得分:4)

在这里,假设您正在使用带有注释的JUnit 4:

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

}

您可能还会发现this article非常有用,尤其是在使用JUnit 3时。

Refer this获取有关JUnit 4的快速帮助。

希望有所帮助。