第一次使用mockito



我以前一直在使用jUnit。现在我想使用Mockito进行学习。

我有一个REST WS,看起来像这样:

@Path("postservice")
public class PostWebService {
private static final Logger logger = Logger.getLogger(PostWebService.class);
//Inject of the stateless post session bean for persisting purposes
@EJB
private PostServiceInterface postService;
/*Webservice for persisting of posts*/
@POST
@Path("postmessage")
@Produces(MediaType.TEXT_PLAIN)
public String insertPost(
        @FormParam("post") String post,
        @Context HttpServletRequest request
) {
    logger.info("insertPost called");
    try {
        request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    User user = (User) request.getSession().getAttribute("user");
    logger.info("Got user from session.");
    if (user != null) {
        postService.insertPost(post, user);
        return "true";
    } else {
        return "false";
    }
}

}

以下测试用例可能是错误的:

@RunWith(MockitoJUnitRunner.class)
public class PostWebServiceTest {
@InjectMocks
PostWebService pws;
@Mock
PostServiceInterface mockedPostService;
@Mock
HttpServletRequest request;
@Mock
User user;
@Mock
HttpSession session;
@Before
public void setUp() throws Exception {
    Logger mockedLogger = mock(Logger.class);
}
@Test
public void testInsertPost() throws Exception {
    PostWebService pws = mock(PostWebService.class);
    String post = "Some post";
    when(pws.insertPost(post, request)).thenReturn("true");
    assertTrue(pws.insertPost(post, request) == "true");
}
}

我已经得到了几个错误,我决定"删除"或使特定的部分通过,看看我还有什么其他错误:

第一个错误:

java.lang.NullPointerException
at se.chas.fakebook.webservices.PostWebService.insertPost(PostWebService.java:41)
at se.chas.fakebook.webservices.PostWebServiceTest.testInsertPost(PostWebServiceTest.java:42)

第41行是:User User=(User)request.getSession().getAttribute("User");第42行是:when(pws.insertPost(post,request)).thenReturn("true");

我将用户对象初始化为null,看看会发生什么,这次我得到了这个错误:

org.mockito.exceptions.base.MockitoException: 
'setCharacterEncoding' is a *void method* and it *cannot* be stubbed with a *return value*!
 Voids are usually stubbed with Throwables:
doThrow(exception).when(mock).someVoidMethod();

然后我删除了setCharacterEncoding方法,测试通过了。为什么之前没有通过?

有了这个设置,Mockito将为PostWebService创建一个普通的Java对象,然后将所有其他mock连接到其中。

这意味着

when(pws.insertPost(post, request)).thenReturn("true");

实际上会尝试执行CCD_ 2,因为CCD_。when()只能安全地用于用@Mock注释的字段。一个很好的例子是这行:

User user = (User) request.getSession().getAttribute("user");

NPE的测试将失败,因为request是一个mock,并且您没有告诉Mockito getSession()返回什么。请使用此设置代码:

when(request.getSession()).thenReturn(session);
when(session.getAttribute("user")).thenReturn(user);
assertEquals("true", pws.insertPost(post, request));

相关内容

  • 没有找到相关文章

最新更新