我正在尝试通过模拟 DAO 来使用 EasyMock 测试服务层。我的 DAO 类中的一种方法如下所示。
public BrickStreamUserVO getUserDetails(String userName, String password)
{
BrickStreamUserVO usrObj = null;
try
{
String sqlStr = "SELECT * FROM USER_T WHERE USER_NAME LIKE '" + userName + "'
AND PASSWORD = '" + password + "'";
usrObj = getJdbcTemplate().queryForObject(sqlStr, new BrickStreamUserMapper());
logger.info("Getting user details....");
if(usrObj==null)
throw new UserException("Invalid Login parameters");
}
catch (Exception e)
{
logger.error(e);
throw new UserException("Invalid Login parameters");
}
return usrObj;
}
这是我的测试代码
public class BrickStreamServiceImplTest
{
private BrickStreamServiceImpl serviceImpl;
@Before
public void buildService()
{
serviceImpl = new BrickStreamServiceImpl();
}
@Test
public void testGetUserDetails()
{
BrickStreamDaoImpl daoImplMock = createMock(BrickStreamDaoImpl.class);
expect(daoImplMock.getUserDetails("user", "pwd")).
andReturn(new BrickStreamUserVO());
replay(daoImplMock);
serviceImpl.setBrickStreamDao(daoImplMock);
serviceImpl.getUserDetails("user", "pwd");
verify(daoImplMock);
}
}
如何测试抛出 UserException 的方法,您可以看到如果 usrObj 对象为 null,它会抛出 UserException。