I'm trying to create test cases for a webservice but I'm getting nullpointerexception. This is the web service:
@Path("friendservice")
public class FriendWebService {
private static final Logger logger = Logger.getLogger(FriendWebService.class);
@EJB
private FriendRequestServiceInterface friendRequestService;
@GET
@Path("friendrequest")
@Produces(MediaType.TEXT_PLAIN)
public String createFriendRequest(
@Context HttpServletRequest request) {
logger.info("createFriendRequest called");
String result = "false";
User user = (User) request.getSession().getAttribute("user");
User otherUser = (User) request.getSession().getAttribute("profileuser");
if ((user != null) && (otherUser != null)) {
logger.info("Got two users from session, creating friend request.");
if (friendRequestService.createFriendRequest(user, otherUser)) {
result = "true";
}
}
return result;
}
}
This is my test class:
public class FriendWebServiceTest {
@Mock
FriendRequestServiceInterface FriendRequestService;
@Mock
Logger mockedLogger = mock(Logger.class);
@Mock
HttpServletRequest mockedRequest = mock(HttpServletRequest.class);
@Mock
HttpSession mockedSession = mock(HttpSession.class);
@Mock
User mockedUser = mock(User.class);
@Mock
User mockedOtherUser = mock(User.class);
@InjectMocks
FriendWebService friendWebService = new FriendWebService();
@Before
public void setUp() throws Exception {
}
@Test
public void testCreateFriendRequest() throws Exception {
when(mockedRequest.getSession()).thenReturn(mockedSession);
when(mockedSession.getAttribute("user")).thenReturn(mockedUser);
when(mockedSession.getAttribute("profileuser")).thenReturn(mockedOtherUser);
when(FriendRequestService.createFriendRequest(mockedUser, mockedOtherUser)).thenReturn(true);
assertTrue(friendWebService.createFriendRequest(mockedRequest) == "true");
}
The NullPointerException occurs at "when(FriendRequestService.createFriendRequest(mockedUser, mockedOtherUser)).thenReturn(true);"
What am I doing wrong?
NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
How to avoid the NullPointerException? To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.
Will This Library Help Overcoming Nullpointerexceptions With Mockito. any()? Answer : Passing Mockito.
Instead of calling initMocks
, You probably need to annotate with @RunWith(MockitoJUnitRunner.class)
to your FriendWebServiceTest
class.
You are chaining method calls on your mocked instance:
@Mock
HttpServletRequest mockedRequest = mock(HttpServletRequest.class);
First of all, you do not need to do both, either use the @Mock
annotation or the mock
method. Like this, you first assign a Mock and then replace this instance with another mock. I recommend the annotation as it adds some context to the mock such as the field's name. This might already cause your NullPointerException
as you however never activate the annotations by calling:
MockitoAnnotations.initMocks(this);
as you do not consequently mock all instances with both measures so far. However, even doing so will further result in your exception, so let's move ahead.
Within friendWebService.createFriendRequest(mockedRequest)
you call:
User user = (User) request.getSession().getAttribute("user");
User otherUser = (User) request.getSession().getAttribute("profileuser");
where you call a method on two mocks for which you did not specify any behavior. These mocks do then by default return null
. You need to specify behavior for this such as:
when(request.getSession()).thenReturn(myMockedSession);
before performing this chained call. Bases on this, you can then specify how to react to calls on this mocked instance such as returning your user mocks.
You can also try adding @RunWith(MockitoJUnitRunner.class)
or @ExtendWith(MockitoExtension.class)
annotations to your FriendWebServiceTest
class for JUnit4 and JUnit5 respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With