编写一个servlet程序,再写一个junit测试类测试它
时间: 2023-06-15 22:06:54 浏览: 123
servlet练习程序
以下是一个简单的Servlet程序示例:
```java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>My Servlet</title></head>");
out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("</body></html>");
}
}
```
以下是一个简单的Junit测试类示例:
```java
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
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 MyServletTest {
@Mock
HttpServletRequest request;
@Mock
HttpServletResponse response;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void test() throws ServletException, IOException {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
// 设置Mock对象的行为
when(response.getWriter()).thenReturn(writer);
// 调用Servlet
new MyServlet().doGet(request, response);
// 验证结果
String expected = "<html><head><title>My Servlet</title></head><body><h1>Hello World!</h1></body></html>";
assertEquals(expected, stringWriter.toString());
}
}
```
该测试类使用Mockito框架模拟HttpServletRequest和HttpServletResponse对象,并使用Junit框架测试doGet()方法的输出是否与预期的相同。
阅读全文