1

我正在尝试通过模拟 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。

4

1 回答 1

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");
}
于 2012-10-08T08:53:58.110 回答