java Mockito 在使用模拟时抛出 NullpointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25912029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:56:05  来源:igfitidea点击:

Mockito throwing a NullpointerException on using a mock

javajunitmockito

提问by Sam Gholizadeh

I'm trying to create test cases for a webservice but I'm getting nullpointerexception. This is the web service:

我正在尝试为 Web 服务创建测试用例,但出现 nullpointerexception。这是网络服务:

@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?

我究竟做错了什么?

回答by Rafael Winterhalter

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 @Mockannotation or the mockmethod. 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 NullPointerExceptionas you however never activate the annotations by calling:

首先,你不需要两者都做,要么使用@Mock注解,要么使用mock方法。像这样,你首先分配一个 Mock,然后用另一个 Mock 替换这个实例。我推荐注释,因为它为模拟添加了一些上下文,例如字段的名称。这可能已经导致您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 then by default return null. You need to specify behavior for this such as:

在您没有指定任何行为的两个模拟上调用方法的地方。这些模拟然后默认返回null。您需要为此指定行为,例如:

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.

在执行此链接调用之前。在此基础上,您可以指定如何对此模拟实例上的调用做出反应,例如返回您的用户模拟。

回答by Peiti Li

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

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