Junit--使用stub测试一个HTTP连接

本文介绍了一个使用Jetty作为嵌入式服务器的JUnit测试案例。通过创建一个简单的HTTP服务器来模拟Web服务响应,验证了服务器返回预期的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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作为嵌入式服务器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值