我正在修改一些继承而来的代码。 我编写了一个测试,旨在捕获NullPointerException(因为它试图从空对象调用方法)。
@Test(expected=NullPointerException.class)
public void checkXRequirement_NullProduct_AddAction_ShouldThrowNullPointerException() throws CustomException {
Site site = mock(Site.class);
Product product = null;
when(BasketHelper.getAction(request)).thenReturn(0);
when(BasketHelper.getActionProduct(site, request)).thenReturn(product);
BasketHelper.requiresX(request, site);
}
相关方法和变量:
public static final int ACTION_ADD = 0;
public static final int ACTION_DELETE = 1;
protected static int getAction(HttpServletRequest a_request) {
String sBuyProduct = a_request.getParameter(ATTRIBUTE_NAME_BUY_PRODUCT);
String sBuyProduct = a_request.getParameter(ATTRIBUTE_NAME_BUY_PRODUCT);
if (sBuyProduct != null) iAction = ACTION_ADD;
else (sDelProduct != null) iAction = ACTION_DELETE;
return iBasketAction
}
protected static Product getActionProduct(Site a_site, HttpServletRequest a_request) {
String sBuyProduct = a_request.getParameter(ATTRIBUTE_NAME_BUY_PRODUCT);
String sDelProduct = a_request.getParameter(ATTRIBUTE_NAME_DEL_PRODUCT);
String sProduct = null;
switch (getBasketAction(a_request)) {
case BASKET_ACTION_ADD:
sProduct = sBuyProduct;
break;
case BASKET_ACTION_DELETE:
sProduct = sDelProduct;
break;
}
int iProductId;
try {
iProductId = Integer.parseInt(sProduct);
} catch (NumberFormatException nbrEx) {
return null;
}
Product prod = getProductById(iProductId);
if (prod.isMasterProduct()) {
prod = getChildProduct(prod, a_site, a_request);
}
return prod;
}
public static boolean requiresX(HttpServletRequest request, Site site) throws CustomException {
try{
if (getAction(request) == ACTION_ADD) {
Product prod = getActionProduct(site, request);
return prod.getType().isRequiredX();
}
} catch(NullPointerException exception) {
log.error("Error Message", exception);
}
return false;
}
运行测试的jUnit结果是失败,并且包含以下堆栈跟踪:
java.lang.Exception: Unexpected exception, expected<java.lang.NullPointerException> but was<org.mockito.exceptions.misusing.WrongTypeOfReturnValue>
Caused by: org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Integer cannot be returned by getParameter()
getParameter() should return String#
我是否误解了 when().thenReturn 应该在这里起作用的方式? 我只想让 getAction 在被调用时返回 0,让 getActionProduct 返回 null。显然,getParameter() 被调用了,但我不知道为什么。
getProduct()
吗? - Sotirios Delimanolis