写一个servlet程序,再写一个简单的junit测试类测试它
时间: 2023-06-16 16:04:35 浏览: 140
测试junit源代码
以下是一个简单的 servlet 程序示例:
```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorldServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Hello World Servlet</title></head><body>");
out.println("<h1>Hello World!</h1>");
out.println("</body></html>");
}
}
```
以下是一个简单的 JUnit 测试类,用于测试上述 servlet 程序:
```java
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class HelloWorldServletTest {
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testDoGet() throws ServletException, IOException {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
HelloWorldServlet servlet = new HelloWorldServlet();
assertEquals("text/html", response.getContentType());
writer.flush();
assertEquals("<html><head><title>Hello World Servlet</title></head><body><h1>Hello World!</h1></body></html>\n", stringWriter.toString());
}
}
```
在此示例中,使用 Mockito 模拟了 HttpServletRequest 和 HttpServletResponse 对象,以便在测试中使用它们。测试方法验证 servlet 的 doGet() 方法是否正确生成了 HTML 响应。
阅读全文