spring - 如何修复 Junit 测试中的空指针异常?
问题描述
当我运行以下 Junit 测试时,我得到了一个空指针异常,如代码所示。有人可以帮我解决吗?
import com.apexsct.pouservice.amq.inboxlistener.GetUpdateAvailablePositionInfo;
import com.apexsct.servcomm.amq.pouservice.dto.DeliveryPositionData;
public class GetUpdateAvailablePositionInfoActionTest {
@Mock
protected PositionRepository positionRepo;
@Mock
protected UserInterfaceGroupRepository uiGroupRepo;
@InjectMocks
private GetUpdateAvailablePositionInfo service;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testEmptyRequest() {
DeliveryPositionData response = (DeliveryPositionData) service.perform(); // NULL POINTER EXCEPTION HERE
assertEquals(ErrorMessageConstant.INVALID_REQUEST, response.getErrMsg());
}
}
解决方案
根据您的测试名称,您想测试请求为空的情况。但是,您仍然需要提供一个实际对象,因为您的代码不处理request
null 的情况。
您可以将测试调整为如下所示:
public class GetUpdateAvailablePositionInfoActionTest {
@Mock
protected PositionRepository positionRepo;
@Mock
protected UserInterfaceGroupRepository uiGroupRepo;
@Mock // creates and injects a mock for the request
UpdAvlbPosRequest request;
@InjectMocks
private GetUpdateAvailablePositionInfo service;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testEmptyRequest() {
// defines that the sn of the request is an empty string
// (Depending on what StringUtils class you use, it might also handle null correctly.
// In this case this line can be removed)
Mockito.when(request.getSn()).thenReturn("");
DeliveryPositionData response = (DeliveryPositionData) service.perform();
assertEquals(ErrorMessageConstant.INVALID_REQUEST, response.getErrMsg());
}
}
推荐阅读
- python - 烧瓶 form.data 值未在提交时更新
- angular - 如何使用 Angular 9 (Ivy) 动态渲染和加载组件
- android - 如何设置文本光标高度以匹配我在 EditText 中的字体
- python - 为什么我收到错误:列表索引超出范围
- flutter - 使用相机功能时,Flutter 应用程序崩溃并从启动画面重新启动
- concurrency - 分布式原子列表:微服务之间的同步
- github - PhpStorm 库看不到库
- aws-batch - aws 批处理:获取过去提交的作业的概览
- java - Cucumber 在 Android Studio 中找不到步骤定义
- android - 使用地图和本地化在 Fragment 上旋转屏幕时出现 KotlinNullPointerException