简体   繁体   English

Mockito 在使用模拟时抛出 NullpointerException

[英]Mockito throwing a NullpointerException on using a mock

I'm trying to create test cases for a webservice but I'm getting nullpointerexception.我正在尝试为 web 服务创建测试用例,但我得到了 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);" NullPointerException 发生在“when(FriendRequestService.createFriendRequest(mockedUser, mockedOtherUser)).thenReturn(true);”

What am I doing wrong?我究竟做错了什么?

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.首先,您不需要同时使用@Mock注释或mock方法。 Like this, you first assign a Mock and then replace this instance with another mock.像这样,你首先分配一个 Mock,然后用另一个 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:这可能已经导致您的NullPointerException因为您从未通过调用激活注释:

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:friendWebService.createFriendRequest(mockedRequest) ,您调用:

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 .这些模拟默认返回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.基于此,您可以指定如何响应对此模拟实例的调用,例如返回您的用户模拟。

而不是调用initMocks ,您可能需要使用@RunWith(MockitoJUnitRunner.class)对您的FriendWebServiceTest类进行注释。

您还可以尝试将@RunWith(MockitoJUnitRunner.class)@ExtendWith(MockitoExtension.class)注释分别添加到 JUnit4 和 JUnit5 的FriendWebServiceTest类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM