首页 > 解决方案 > 如何修复 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());
    }

}

标签: springjunitnullpointerexceptionmockito

解决方案


根据您的测试名称,您想测试请求为空的情况。但是,您仍然需要提供一个实际对象,因为您的代码不处理requestnull 的情况。

您可以将测试调整为如下所示:

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());
    }
}


推荐阅读