1. 程式人生 > >JUNIT——使用Mockserver模擬server返回json字串

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