mock http server

系统集成测试时,需要调用其他系统,但是为了单元测试,可以模拟http服务器,即mock httpserver

 

http://wink.apache.org/ 用到一个东东,这个比较好用

 

maven 代码

<dependency>
			<groupId>org.apache.wink</groupId>
			<artifactId>wink-component-test-support</artifactId>
			<version>1.3.0</version>
			<scope>test</scope>
		</dependency>

 

ps;用到sjf4j版本为1.6以上,调试时纠结了半天。

代码为:

package com.vipshop.gmj.server.gm.core.test.service.impl;

import java.util.List;

import org.apache.wink.client.MockHttpServer;
import org.apache.wink.client.MockHttpServer.MockHttpServerResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.vipshop.gmj.server.framework.util.JSonUtil;
import com.vipshop.gmj.server.framework.util.web.HttpGetMethodUtil;
import com.vipshop.gmj.server.gm.core.test.pojo.PojoTest;

public class TestMockServer {
	MockHttpServer mockServer ;
	final int PORT = 4999;
	String  URL_PRE_FIX = "http://127.0.0.1";
	
	@Before
	public void startServer(){
		mockServer = new MockHttpServer(PORT);
		mockServer.startServer();
		
		URL_PRE_FIX = URL_PRE_FIX +":"+mockServer.getServerPort();
		
		System.out.println(mockServer.getServerPort());
		mockServer.getMockHttpServerResponses();
		HttpGetMethodUtil.sendUrl(URL_PRE_FIX, null);
	}
	
	public void setContent(Object content){
		MockHttpServerResponse response = new MockHttpServerResponse();
		
	    response.setMockResponseContent(JSonUtil.toJSonString(content));
	    response.setMockResponseCode(200);
	    response.setMockResponseContentType("application/json");
	    
	    List<MockHttpServerResponse> list = mockServer.getMockHttpServerResponses();
	    list.add(response);
//	    mockServer.setMockHttpServerResponses(response);
	}
	
	@Test
	public void testMockServer(){
		PojoTest p1 = new PojoTest();
		p1.setId(1);
	    p1.setFirstName("huang");
	    p1.setLastName("jiguang");
	    
	    
	    setContent(p1);
	    p1.setId(2);
	    setContent(p1);
	    
		String s1 =  HttpGetMethodUtil.sendUrl(URL_PRE_FIX, null);
		String s2 =  HttpGetMethodUtil.sendUrl(URL_PRE_FIX, null);
		
	    System.out.println("s1:"+s1);
	    System.out.println("s2:"+s2);
	} 
	
	@After
	public void stopServer(){
		mockServer.stopServer();
	}
	
}

 

List<MockHttpServerResponse> list = mockServer.getMockHttpServerResponses();

 

mockserver 里面有个队列,保存着response的list,我加入一个response,我取走这个response,就没了

 

ok。端口那个,好像设置为4999后,其实会为5000端口。

 

 

你可能感兴趣的:(java,test,mock,httpserver)