JUNIT——使用Mockserver模拟server返回json字符串

执行请求之前执行如下mockServer方法,所以最好写在@Before中:

private ClientAndServer mockServer;

@Before
public void setUp() throws IOException {
    mockServer();
}

 

public void mockServer(){
//要请求的cmd代码:
//curl -X GET http://10.100.100.10:31000/api/a/alarms/pageFiltered?sourceObject="abcd"
//MockServerClient的方式没弄懂,所以先注释掉,用startClientAndServer方式
//		new MockServerClient("localhost", 31000)
//	    .when(
//	        request()
//	            .withPath("/api/alma/alarms/pageFiltered")
//	    )
//	    .respond(
//	        response()
//	            .withBody("some_response_body")
//	    );
		
		mockServer = startClientAndServer(31000);
		mockServer
		.when(
		request()
		.withMethod("GET")
		.withPath("/api/alma/alarms/pageFiltered")
		.withBody("{sourceObject: 'INGESTER-CMIngester_netact01'}")
		)
		.respond(
		response()
		.withStatusCode(200)
//       注释掉的代码部分应该没什么用,没有影响
//		.withCookie(
//		"sessionId", "2By8LOhBmaW5nZXJwcmludCIlMDAzMW"
//		)
//		.withHeaders(
//		new Header("Content-Type", "application/json; charset=utf-8"),
//		new Header("Cache-Control", "public, max-age=86400")
//		)

//      这里的jsonStr是一个String的json字符串,自己按需定义吧
		.withBody(jsonStr)
//      例如:
//		.withBody("{ \"apply_id\": \"000001\", \"overdued\": \"Y\" }")

		);

	}

测试代码:

@Test
	public void testRunCommand() {
		String calarmService = "localhost:31000";
		AlarmManager.runCommand(calarmService);

		assertTrue(true);
	}

被测试的runCommand()方法如下:

//例如:String url = "10.100.100.10:31000";
private static String runCommand(String url) {
		StringBuffer output = new StringBuffer();
	    try { 
	    	String commandStr = "curl -X GET http://" + url +"/api/a/alarms/pageFiltered?sourceObject="+ParameterUtils.getSDN();
	    	LOGGER.debug(commandStr);
	    	Process process = Runtime.getRuntime().exec(commandStr);  
	        InputStream input = process.getInputStream();
	        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
	        String szline;
	        while ((szline = reader.readLine())!= null) {
	            output.append(szline.replace("@", "") + "\n");
	        }
	        input.close();
	        reader.close();
	        process.waitFor();
	        process.destroy();
	    } catch (Exception e) {  
	    	LOGGER.warn(e);
	        return null;
	    }
	    return output.toString();
        //这样最后就返回了jsonStr
	
	}

最后别忘了关闭:

@After
	public void tearDown() throws IOException {
		mockServer.stop();
	}

 

参考文章:

https://www.cnblogs.com/wangdaijun/p/6802892.html

你可能感兴趣的:(JAVA,JUnit)