Issue
I'm getting a Null Pointer Exception as shown in the code when I run the following Junit test. Can someone please help me fix it?
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());
}
}
Solution
Based on your test name you want to test a case where the request is empty.
However you still need to supply an actual object, as your code does not
handle the case where request
is null.
You could adjust the test to look like this:
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());
}
}
Answered By - second