第一次使用mockito

时间:2014-09-18 09:25:56

标签: java junit 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 =(用户)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方法并传递了测试。为什么以前没有通过?

1 个答案:

答案 0 :(得分:2)

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

这意味着

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

实际上会尝试执行insertPost(),因为pws本身并不是模拟。 when()只能安全地用于使用@Mock注释的字段。这一行就是一个很好的例子:

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

由于您request是模拟器,因此测试将因NPE而失败,并且您没有告诉Mockito getSession()要返回什么。请改用此设置代码:

when(request.getSession()).thenReturn(session);
when(session.getAttribute("user")).thenReturn(user);

assertEquals("true", pws.insertPost(post, request));