Sam Gholizadeh
Sam Gholizadeh

Reputation: 237

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?

Upvotes: 16

Views: 50593

Answers (3)

Rafael Winterhalter
Rafael Winterhalter

Reputation: 44032

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 by default return null. You need to specify behavior for this such as:

when(request.getSession()).thenReturn(myMockedSession);

before performing this chained call. Based on this, you can then specify how to react to calls on this mocked instance such as returning your user mocks.

Upvotes: 22

Tafadzwa Chimberengwa
Tafadzwa Chimberengwa

Reputation: 409

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

Upvotes: 2

P Li
P Li

Reputation: 5222

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

Upvotes: 2

Related Questions