我正在尝试为我主要使用HttpServlet的项目实现测试。我需要为所有获取和发布编写一些测试。
我尝试搜索如何使用Mockito和类似的库编写测试,但是我只得到了空指针错误。
这是我要测试的功能。
package Handlers;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/")
public class Index extends HttpServlet {
public Index() {
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write("<h1>Welcome to my index page</h1><h2>This is all</h2>");
resp.setStatus(HttpServletResponse.SC_ACCEPTED);
}
}
使用以下测试代码,我可以使测试通过并获得100%的测试覆盖率,但这实际上是硬编码的。
@Test
public void TestDoGet() throws ServletException, IOException {
HttpServletResponse response = mock(HttpServletResponse.class);
HttpServletRequest request = mock(HttpServletRequest.class);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
when(response.getWriter()).thenReturn(pw);
when(response.getStatus()).thenReturn(202); // Hardcode
Index index = new Index();
index.doGet(request, response);
assertEquals(202, response.getStatus());
}
我确实尝试仅在该功能上使用Unirest.Get()
,但确实可以,但是我得到了0%的测试覆盖率。