如何在Mockito JUnit中进行单元测试设置方法

问题描述 投票:0回答:1

我想模拟或存根,我是单元测试的新手。

我有以下方法。这是方法HttpServletRequest请求

的参数

Request.getSession()。setAttribute(“ email”,“ [email protected]”);

我确实尝试过doCallRealMethod,但我正在学习。如何使用Mockito对上述方法进行单元测试?

我想验证该方法发送或插入这两个参数。

java junit mockito
1个回答
0
投票

假设您必须测试一些servlet,我建议采用这种方法

HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
HttpSession session = Mockito.mock(HttpSession.class);
Mockito.doReturn(session).when(req).getSession();

myHttpServlet.service(req, res);

Mockito.verify(req, Mockito.times(1)).getSession();
Mockito.verify(session, Mockito.times(1)).setAttribute(
        ArgumentMatchers.eq("email"), ArgumentMatchers.eq("[email protected]"));
Mockito.verifyNoMoreInteractions(session, req);
© www.soinside.com 2019 - 2024. All rights reserved.