如何在Junit测试中修复Null Pointer异常?

时间:2019-08-23 15:04:49

标签: spring junit nullpointerexception mockito

当我运行以下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());
    }

}

1 个答案:

答案 0 :(得分:0)

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

您可以将测试调整为如下形式:

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