Junit测试类
package cn.howe.lis.jetty;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mortbay.jetty.HttpHeaders;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.AbstractHandler;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.util.ByteArrayISO8859Writer;
public class JettyTest {
private static JettyTest jettyTest;
@BeforeClass
public static void setUp() throws Exception {
Server server = new Server(8080);
jettyTest = new JettyTest();
Context contentOKContent = new Context(server, "/testGetContentOk");
contentOKContent.setHandler(jettyTest.new GetContentOKHandlerTest());
server.setStopAtShutdown(true);
server.start();
}
public void tearDown() {}
@Test
public void testGetContentOk() throws Exception {
WebClient client = jettyTest.new WebClient();
String result = client.getContent(new URL("http://localhost:8080/testGetContentOk"));
assertEquals("stub use jetty, it works", result);
}
// 内部类
private class GetContentOKHandlerTest extends AbstractHandler {
@Override
public void handle(String target, HttpServletRequest req, HttpServletResponse resp, int dispatch)
throws IOException, ServletException {
OutputStream out = resp.getOutputStream();
ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer();
writer.write("stub use jetty, it works");
writer.flush();
resp.setIntHeader(HttpHeaders.CONTENT_LENGTH, writer.size());
writer.writeTo(out);
out.flush();
}
}
private class WebClient {
public String getContent(URL url) {
StringBuffer content = new StringBuffer();
try
{
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
InputStream is = connection.getInputStream();
byte[] buffer = new byte[2048];
int count;
while (-1 != (count = is.read(buffer)))
{
content.append(new String(buffer, 0, count));
}
}
catch ( IOException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return content.toString();
}
}
}
使用stub替换Web服务器资源,使用Jetty作为嵌入式服务器。