我之前一直在使用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方法,测试通过了。为什么之前没有通过呢?