Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
One, foreword
Do the performance test script is a practical effort, the work is common key-value, JSON mode is more, then the nGrinder script how we write the following brief introduction.
Implement a GET request demo
First, write a project through SpringBoot to implement add, delete, change and check, through Get request:
http://localhost:8888/findinfo?username=600128
Copy the code
The project Controller layer uses the simplest Get request to query data, the code is:
@GetMapping("/findinfo")
@ResponseBody
public List<UserTable> findUser(UserTable userInfo) {
List<UserTable> UserInfo = userService.findinfo(userInfo);
return UserInfo;
}
Copy the code
The @responseBody annotation automatically converts the Json display to the page. This project is very simple, do not show other code, you can find your own company’s project or write a demo project, practice.
The interface layer:
public interface UserService {
List<UserTable> findinfo(UserTable userInfo);
}
Copy the code
Implementation layer:
@Service
public class UserServiceImpl implements UserService {
@Override
public List<UserTable> findinfo(UserTable userInfo) {
UserTableExample example = new UserTableExample();
UserTableExample.Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo(userInfo.getUsername());
returnuserTableMapper.selectByExample(example); }}Copy the code
Database Dao layer:
- This layer is generated through the Generator plug-in
Generator plugin reference code:
<! DOCTYPEgeneratorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<! Database driver: Select the database driver package on your local hard drive -->
<classPathEntry location=".. \ mysql - manager \ lib \ mysql connector - Java - 5.1.6. Jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<! -- Whether to remove automatically generated comments true: yes: false: no -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<! -- Database link URL, username, password -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/7d"
userId="root" password="123456">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<! The package name and location of the generated model
<javaModelGenerator targetPackage="com.sevendgrop.pojo" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<! Generate mapping file package name and location -->
<sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<! The package name and location where the DAO was generated
<javaClientGenerator type="XMLMAPPER" targetPackage="com.sevendgrop.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<! TableName is the name of the table in the database or the name of the view.
<table schema="" tableName="case_table"></table>
</context>
</generatorConfiguration>
Copy the code
Pom. XML configuration:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
<! Mybatis Generator plugin for automatic code generation
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>
Copy the code
Maven plugin:
After configuring the above, click:
Run to generate database connection SQL statements.
Script writing
Open the source deployment project in the previous section, create a new script where the source running script is introduced, and modify it into your own practice script by referring to the following code.
The new script in the nGrinder writes the following code:
import org.junit.FixMethodOrder
import static net.grinder.script.Grinder.grinder
import static org.junit.Assert.*
import static org.hamcrest.Matchers.*
import net.grinder.plugin.http.HTTPRequest
import net.grinder.plugin.http.HTTPPluginControl
import net.grinder.script.GTest
import net.grinder.script.Grinder
import net.grinder.scriptengine.groovy.junit.GrinderRunner
import net.grinder.scriptengine.groovy.junit.annotation.BeforeProcess
import net.grinder.scriptengine.groovy.junit.annotation.BeforeThread
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
import java.util.Date
import java.util.List
import java.util.ArrayList
import HTTPClient.Cookie
import HTTPClient.CookieModule
import HTTPClient.HTTPResponse
import HTTPClient.NVPair
@RunWith(GrinderRunner)
class PostGetDemo {
public static GTest test
// Define HTTPRequest static variable request, used to send HTTP requests
public static HTTPRequest request
// Define NVPair headers to store generic request header data
public static NVPair[] headers = []
// define NVPair array params to store request parameter data
public static NVPair[] params = []
// Define Cookie array cookies to store generic Cookie data
public static Cookie[] cookies = []
@BeforeProcess
public static void beforeProcess(a) {
// Set request response timeout (ms)
HTTPPluginControl.getConnectionDefaults().timeout = 6000
// Create a GTest object. The first parameter 1 represents the order ID of the execution when there are multiple requests/transactions. The second parameter is the name of the request/transaction, which is displayed in the summary result
test = new GTest(1."localhost:8888")
// Create an HTTPRequest object to initiate an HTTP request
request = new HTTPRequest()
// Set header datas
List<NVPair> headerList = new ArrayList<NVPair>()
headerList.add(new NVPair("Content-Type"."application/x-www-form-urlencoded"))
headerList.add(new NVPair("Connection"."keep-alive"))
headers = headerList.toArray()
// Set param datas
List<NVPair> paramList = new ArrayList<NVPair>()
paramList.add(new NVPair("username"."600128"))
params = paramList.toArray()
// Set cookie datas
List<Cookie> cookieList = new ArrayList<Cookie>()
cookieList.add(new Cookie("Cookie"."Idea-96adee05=87213429-7753-4183-99d0-c1c3362ce5d0; Hm_lvt_eb54a8c74fe4cb91ad8ca004e48cd3f9=1545999605; Pycharm-5b892e29=6772acb9-e87b-4d37-98e3-bff82e412d17; csrftoken=KDr8oYtD0gKh7UbS5fWSROzEOX6rjX3CN26pz9PQu9AczLMGFhw53ZrjAhoIOTE7; Hm_lvt_f2c884fc06fca522c4105429259b8a73=1558506687; Webstorm-173930bd=052a6829-b802-4eb0-a1e2-e348f1012604; _ga = GA1.1.1061327805.1562753587; UM_distinctid=16c02a6b049e1-02b6b032525db4-e343166-144000-16c02a6b04a120; CNZZDATA4617777=cnzz_eid%3D1637582848-1563412391-%26ntime%3D1563412391; Hm_lvt_0cb375a2e834821b74efffa6c71ee607=1563412574; bad_id22bdcd10-6250-11e8-917f-9fb8db4dc43c=a32ab941-a8f9-11e9-9989-93f7b4f25032; Idea-2b3f02ca=87213429-7753-4183-99d0-c1c3362ce5d0; cookie_lang=0; JSESSIONID=801DE60D9A00C391F80ABE0CD94A6E25"."localhost:8888"."".new Date(), true))
cookies = cookieList.toArray()
grinder.logger.info("before process.");
}
@BeforeThread
public void beforeThread(a) {
// Register the event, start test, the second argument should be consistent with the @test annotation method name, there are multiple requests/transactions, register multiple events
test.record(this."test")
// Configure delay in reporting statistics results
grinder.statistics.delayReports = true;
grinder.logger.info("before thread.");
}
@Before
public void before(a) {
// Here you can add headers attributes and cookies
//request.setHeaders(headers)
cookies.each { CookieModule.addCookie(it, HTTPPluginControl.getThreadHTTPClientContext()) }
grinder.logger.info("before thread. init headers and cookies");
}
@Test
public void test(a) {
// Send a GET request
HTTPResponse result = request.GET("http://localhost:8888/findinfo", params)
def text = result.getText()
grinder.logger.info(text)
// Assert the HTTP request status code
assertThat(result.statusCode, is(200))}}Copy the code
Run again:
Click Run Configuration to add:
- javaagent: D: \ maven \ repository \.net, sf, the grinder, the grinder - DCR - agent \ 3.9.1 \ the grinder - DCR - agent - 3.9.1. JarCopy the code
The configuration description is as follows:
Then click Run:
The results are as follows:
Key points to note here:
List<NVPair> headerList = new ArrayList<NVPair>()
headerList.add(new NVPair("Content-Type"."application/x-www-form-urlencoded"))
headerList.add(new NVPair("Connection"."keep-alive"))
headers = headerList.toArray()
Copy the code
Note the header:
public static NVPair[] headers = []
public static NVPair[] params = []
public static Cookie[] cookies = []
Copy the code
Check the source code to know how to pass the value, here is a list of cookie source value:
Read the source code to learn that if the cookie needs to pass the new cookie entity through the constructor to pass the value in:
List<Cookie> cookieList = new ArrayList<Cookie>()
cookieList.add(new Cookie("Cookie"."Idea-96adee05=87213429-7753-4183-99d0-c1c3362ce5d0; Hm_lvt_eb54a8c74fe4cb91ad8ca004e48cd3f9=1545999605; Pycharm-5b892e29=6772acb9-e87b-4d37-98e3-bff82e412d17; csrftoken=KDr8oYtD0gKh7UbS5fWSROzEOX6rjX3CN26pz9PQu9AczLMGFhw53ZrjAhoIOTE7; Hm_lvt_f2c884fc06fca522c4105429259b8a73=1558506687; Webstorm-173930bd=052a6829-b802-4eb0-a1e2-e348f1012604; _ga = GA1.1.1061327805.1562753587; UM_distinctid=16c02a6b049e1-02b6b032525db4-e343166-144000-16c02a6b04a120; CNZZDATA4617777=cnzz_eid%3D1637582848-1563412391-%26ntime%3D1563412391; Hm_lvt_0cb375a2e834821b74efffa6c71ee607=1563412574; bad_id22bdcd10-6250-11e8-917f-9fb8db4dc43c=a32ab941-a8f9-11e9-9989-93f7b4f25032; Idea-2b3f02ca=87213429-7753-4183-99d0-c1c3362ce5d0; cookie_lang=0; JSESSIONID=801DE60D9A00C391F80ABE0CD94A6E25"."localhost:8888"."".new Date(), true))
cookies = cookieList.toArray()
grinder.logger.info("before process.");
Copy the code
The @beforeThread annotation will execute the test.record method.
/**
* Instrument the supplied {@code target} object's method which has the given name. Subsequent
* calls to {@code target}'s given method will be recorded against the statistics for this
* {@codeTest}. * provides {with the given name@codeTarget} object method. Subsequent pair {@codeTarget} The call to a given method will be logged based on statistics for this method *@param target Object to instrument.
* @param methodName method name to instrument
* @throws NonInstrumentableTypeException If {@code target} could not be instrumented.
* @since3.2.1 * /
public final void record(Object target, String methodName) throws NonInstrumentableTypeException {
if (StringUtils.isNotEmpty(context)) {
record(target, newMethodNameFilter(methodName)); }}Copy the code
Explanation:
- Target: script object, in this case this;
- MethodNam: is the name of the method to be counted, usually by
@Test
Annotation method. If not configured, the method executes normally, but there is no system
Calculating result data;
The following code can be copied and modified
import org.junit.FixMethodOrder
import static net.grinder.script.Grinder.grinder
import static org.junit.Assert.*
import static org.hamcrest.Matchers.*
import net.grinder.plugin.http.HTTPRequest
import net.grinder.plugin.http.HTTPPluginControl
import net.grinder.script.GTest
import net.grinder.script.Grinder
import net.grinder.scriptengine.groovy.junit.GrinderRunner
import net.grinder.scriptengine.groovy.junit.annotation.BeforeProcess
import net.grinder.scriptengine.groovy.junit.annotation.BeforeThread
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
import java.util.Date
import java.util.List
import java.util.ArrayList
import HTTPClient.Cookie
import HTTPClient.CookieModule
import HTTPClient.HTTPResponse
import HTTPClient.NVPair
@RunWith(GrinderRunner)
class PostGetDemo {
public static GTest test
// Define HTTPRequest static variable request, used to send HTTP requests
public static HTTPRequest request
// Define NVPair headers to store generic request header data
public static NVPair[] headers = []
// define NVPair array params to store request parameter data
public static NVPair[] params = []
// Define Cookie array cookies to store generic Cookie data
public static Cookie[] cookies = []
@BeforeProcess
public static void beforeProcess(a) {
// Set request response timeout (ms)
HTTPPluginControl.getConnectionDefaults().timeout = 6000
// Create a GTest object. The first parameter 1 represents the order ID of the execution when there are multiple requests/transactions. The second parameter is the name of the request/transaction, which is displayed in the summary result
test = new GTest(1."localhost:8888")
// Create an HTTPRequest object to initiate an HTTP request
request = new HTTPRequest()
// Set header datas
List<NVPair> headerList = new ArrayList<NVPair>()
headerList.add(new NVPair("Content-Type"."application/x-www-form-urlencoded"))
headerList.add(new NVPair("Connection"."keep-alive"))
headers = headerList.toArray()
// Set param datas
List<NVPair> paramList = new ArrayList<NVPair>()
paramList.add(new NVPair("username"."600128"))
params = paramList.toArray()
// Set cookie datas
List<Cookie> cookieList = new ArrayList<Cookie>()
cookieList.add(new Cookie("Cookie"."Idea-96adee05=87213429-7753-4183-99d0-c1c3362ce5d0; Hm_lvt_eb54a8c74fe4cb91ad8ca004e48cd3f9=1545999605; Pycharm-5b892e29=6772acb9-e87b-4d37-98e3-bff82e412d17; csrftoken=KDr8oYtD0gKh7UbS5fWSROzEOX6rjX3CN26pz9PQu9AczLMGFhw53ZrjAhoIOTE7; Hm_lvt_f2c884fc06fca522c4105429259b8a73=1558506687; Webstorm-173930bd=052a6829-b802-4eb0-a1e2-e348f1012604; _ga = GA1.1.1061327805.1562753587; UM_distinctid=16c02a6b049e1-02b6b032525db4-e343166-144000-16c02a6b04a120; CNZZDATA4617777=cnzz_eid%3D1637582848-1563412391-%26ntime%3D1563412391; Hm_lvt_0cb375a2e834821b74efffa6c71ee607=1563412574; bad_id22bdcd10-6250-11e8-917f-9fb8db4dc43c=a32ab941-a8f9-11e9-9989-93f7b4f25032; Idea-2b3f02ca=87213429-7753-4183-99d0-c1c3362ce5d0; cookie_lang=0; JSESSIONID=801DE60D9A00C391F80ABE0CD94A6E25"."localhost:8888"."".new Date(), true))
cookies = cookieList.toArray()
grinder.logger.info("before process.");
}
@BeforeThread
public void beforeThread(a) {
// Register the event, start test, the second argument should be consistent with the @test annotation method name, there are multiple requests/transactions, register multiple events
test.record(this."test")
// Configure delay in reporting statistics results
grinder.statistics.delayReports = true;
grinder.logger.info("before thread.");
}
@Before
public void before(a) {
// Here you can add headers attributes and cookies
//request.setHeaders(headers)
cookies.each { CookieModule.addCookie(it, HTTPPluginControl.getThreadHTTPClientContext()) }
grinder.logger.info("before thread. init headers and cookies");
}
@Test
public void test(a) {
// Send a GET request
HTTPResponse result = request.GET("http://localhost:8888/findinfo", params)
def text = result.getText()
grinder.logger.info(text)
// Assert the HTTP request status code
assertThat(result.statusCode, is(200))}Copy the code
Source code address:
- Github.com/zuozewei/bl…