检查异常时EasyMock TestCase失败

时间:2014-07-15 12:10:15

标签: java easymock

我使用EasyMock为我的代码编写了一个测试用例来检查BusinessServiceException。但是测试用例失败了(不是错误)。任何人都可以告诉我它为什么会发生。这就是为什么这个测试用例失败了。

Java代码:

 public class ListHelper {
    @Resource(name = "shoppingListService")
    private ShoppingListService shoppingListService;
    public void setShoppingListService(ShoppingListService shoppingListService) {
            this.shoppingListService = shoppingListService;
        }


        Public Map<String, String> getShoppingListCount(String partnerId, String userId){
                // Shopping List Section
                Map<String, String> shoppingListDetails = null;
                try {
                    shoppingListDetails = shoppingListService.getShoppingListTotal(partnerId, userId);
                } catch (BusinessServiceException e) {
                }
                return shoppingListDetails;
            }

EasyMock测试:

@Test(expected= BusinessServiceException.class)
public void testGetShoppingListCountBusinessServiceException() throws BusinessServiceException{

    EasyMock.expect(shoppingListService.getShoppingListTotal("p120-90", "2012")).andThrow(new BusinessServiceException("Failure"));
    EasyMock.replay(shoppingListService);
    try{
    listHelper.getShoppingListCount("p120-90", "2012");
    }finally{
    EasyMock.verify(shoppingListService);
    }
}

1 个答案:

答案 0 :(得分:1)

  • 您的方法不会抛出异常,因为您在空的catch区块中将其丢弃。

您应该将方法更改为以下内容:

public Map<String, String> getShoppingListCount(String partnerId, String userId) throws BusinessServiceException {
    // Shopping List Section
    Map<String, String> shoppingListDetails = shoppingListService.getShoppingListTotal(partnerId, userId); // do not catch the possible exception

    return shoppingListDetails;
}
  • 您的测试代码未将模拟传递给受测试的类。

测试看起来像这样:

@Test(expected= BusinessServiceException.class)
public void testGetShoppingListCountBusinessServiceException() throws BusinessServiceException {

    EasyMock.expect(shoppingListService.getShoppingListTotal("p120-90", "2012")).andThrow(new BusinessServiceException("Failure"));
    EasyMock.replay(shoppingListService);

    // pass the mock!
    ListHelper listHelper = new ListHelper(shoppingListService);

    try{
        listHelper.getShoppingListCount("p120-90", "2012");
    }finally{
        EasyMock.verify(shoppingListService);
    }
}