Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito throwing a NullpointerException on using a mock

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?

like image 846
Sam Gholizadeh Avatar asked Sep 18 '14 11:09

Sam Gholizadeh


People also ask

How do I solve NullPointerException in Junit?

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 do I stop NullPointerException?

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.

Which among the following library will help to overcome NullPointerException with Mockito?

Will This Library Help Overcoming Nullpointerexceptions With Mockito. any()? Answer : Passing Mockito.


3 Answers

Instead of calling initMocks, You probably need to annotate with @RunWith(MockitoJUnitRunner.class) to your FriendWebServiceTest class.

like image 156
Peiti Li Avatar answered Oct 22 '22 12:10

Peiti Li


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.

like image 37
Rafael Winterhalter Avatar answered Oct 22 '22 10:10

Rafael Winterhalter


You can also try adding @RunWith(MockitoJUnitRunner.class) or @ExtendWith(MockitoExtension.class) annotations to your FriendWebServiceTest class for JUnit4 and JUnit5 respectively.

like image 24
Tafadzwa Chimberengwa Avatar answered Oct 22 '22 11:10

Tafadzwa Chimberengwa