我试图通过模拟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。
答案 0 :(得分:1)
如果您模拟getUserDetails
方法,则无法测试其行为。
您可能想要提取一个执行用户查询的方法,然后模拟它。
public BrickStreamUserVO queryForUser(String userName, String password) {
String sqlStr = "SELECT * FROM USER_T WHERE USER_NAME LIKE '" + userName + "'
AND PASSWORD = '" + password + "'";
return getJdbcTemplate().queryForObject(sqlStr, new BrickStreamUserMapper());
}
public BrickStreamUserVO getUserDetails(String userName, String password)
{
BrickStreamUserVO usrObj = null;
try
{
usrObj = queryForUser(userName, password);
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;
}
在您的测试课程中:
@Test(expected = UserException.class)
public void testGetUserDetails()
{
BrickStreamDaoImpl daoImplMock = createMockBuilder(BrickStreamDaoImpl.class).addMockedMethod("queryForUser").createMock();
expect(daoImplMock.queryForUser("user", "pwd")).andReturn(null);
replay(daoImplMock);
serviceImpl.setBrickStreamDao(daoImplMock);
serviceImpl.getUserDetails("user", "pwd");
}