标签:
在使用jmeter中Junit的功能之前,最好将接口以手动的方式调通,可以参考 Jmeter之HTTP Request
下面开始讲一下如何使用Junit功能
1. 编写测试类 JmeterJunit 代码如下
package com.test.junit; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import org.junit.After; import org.junit.Before; import org.junit.Test; public class JmeterJunit { public String urlPath = "http://www.mocky.io/v2/572ee171120000332519491b"; public HttpURLConnection connection = null; public OutputStream output = null; public BufferedReader reader = null; public static String request = "{ \"type\": \"getName\"}"; @Before public void setUp() throws Exception { URL url = new URL(urlPath); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-type", "application/json"); connection.setRequestProperty("Content-encoding", "UTF-8"); connection.setRequestProperty("Accept", "application/json"); connection.connect(); } @After public void tearDown() throws Exception { if (null != output) { try { output.close(); } catch (IOException e) { throw e; } } if (null != reader) { try { reader.close(); } catch (IOException e) { throw e; } } if (null != connection) { connection.disconnect(); } } public void sendRequest(String request) throws Exception { output = connection.getOutputStream(); output.write(request.getBytes()); output.flush(); } public String getResponse() throws Exception { reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); String st; StringBuffer stb = new StringBuffer(); while (null != (st = reader.readLine())) { stb.append(st); } return stb.toString(); } @SuppressWarnings("deprecation") public void checkResponse(String response,String name) throws Exception { boolean actualResult = response.contains(name); assertTrue("the expected status is " + name + ", but now it‘s not", actualResult); } @Test public void test1() throws Exception { sendRequest(request); checkResponse(getResponse(),"Brett"); } @Test public void test2() throws Exception { sendRequest(request); checkResponse(getResponse(),"Jason"); } @Test public void test3() throws Exception { sendRequest(request); checkResponse(getResponse(),"Elliotte"); } }
代码中的请求地址和响应信息在Jmeter之HTTP Request中都有描述,这边不多说。在代码中,编写了三个测试方法,分别检查响应中是否包含Brett、Jason以及Elliotte这三个名字。
2. 调试用例,结果如下
3.调试通过后,导出Jar包,并将该Jar包导入到.\Jmeter\apache-jmeter-2.13\lib\junit目录下。(如果编写代码时,存在第三方Jar包引入,那么就将该第三方Jar包放在.\Jmeter\apache-jmeter-2.13\lib中)
4. 重新启动Jmeter,添加三条Junit Request、查看结果树以及图形结果。
5点击运行按钮,可以在查看结果树中查看结果,如果想要将测试结果保存到文件,可以如下图配置
标签:
原文地址:http://www.cnblogs.com/moonpool/p/5465987.html