id=”js_tags” class=”article-tag__list”> included in the collection #Java
id=”js_article-tag-card__right” class=”article-tag-card__right”> 1
Postman The most underrated feature, the efficiency of automated interface testing is simply unbeatable!
This article is aimed at readers who have mastered the basic usage of Postman, that is, have a certain understanding of interface-related concepts and already know how to use Postman to simulate requests.
Current environment:
-
Window 7 – 64
-
Postman version (free version): Chrome App v5.5.3
The UI and some functional locations of different versions of the page will be a little different, but the impact will not be great.
Let’s first think about what else we need to do on basic mock requests if we need to achieve the effect of automated interface testing?
Below I roughly summarize 3 questions (more additions and suggestions are welcome):
- how
-
to determine whether the interface request is successful
-
how to conduct batch and regular interface testing
-
How to deal with dependent interface problems (such as the interface for product orders must require login first),
and
so the next is mainly divided into 3 parts to solve these 3 problems.
Interface result judgment
First of all, since it is an automated test, we definitely need a tool (Postman) or code to help us directly determine whether the result is as expected. Then in the interface test, there are generally two ideas:
- judge whether the code returned by the request
-
meets
-
expected judgment whether the content returned by the request contains the expected content (keywords).
the
Let’s take a look at how to use Postman to solve the above problem:
Ribbon

In Postman, the related functions are very conspicuous, and the use of the Tests function requires us to have a certain programming language foundation, and the currently supported scripting language is JavaScript. But the better point is that we don’t need to think about the context and the running environment, which means that we only need to complete the code block that determines the logic of the result here.
Postman also provides us with some commonly used code templates, in the SNIPPETS ribbon on the right side of the Tests panel, so it is not a problem to know much about JavaScript. Code writing is described in more detail below.
Looking
at the code part of the figure above, we can find the three variables of responseCode, responseBody and tests (which can be used directly):
-
responseBody
: The data content (type string) put back for the interface request -
tests
: is a key-value pair that indicates whether our test results were successful or not, and is finally displayed in Test Results. -
key
:(e.g., code 200) we can use as a description of the result -
: its value is boolean, and ture indicates that the test passed. false indicates that the test failed.
> responseCode
: Contains the status information returned by
the request (for example: code)
value
So the above code should not be difficult to understand, and with the data that returns the result and the way to indicate the success of the result, then our “interface result judgment” problem is basically solved.
There are also a few more commonly used
:
-
time postman: can do more, such as
-
gets the header information of the returned data:
postman.getResponseHeader("")
-
sets the global variable:
postman.setGlobalVariable("variable_key", "variable_value");
>responseTime: The request takes a long
Code
TemplatesPostman provides us with code templates in the SNIPPETS ribbon that can already solve most of the cases, so let’s first select a few related to result judgment to explain
:
Status code : Code is 200Determine
the
request based on the returned code tests["Status code is 200
"] = responseCode.code === 200;
Response body: Contains string
determines whether a "keyword" exists in the returned content. (The key of tests can be modified and will no longer be emphasized)
tests["Body matches string"] = responseBody.has("This can be changed to the keyword content you want to judge"); As mentioned above:
Determine whether there is a access_token keyword
tests["has access_token"] = responseBody.has("access_token");
Response body: is equal to string
to determine whether the returned content is exactly equal as expected.
tests["Body is correct"] = responseBody === "Here you can change it to what you expect";
Response body: JSON value check
As mentioned above, responseBody is a string type and supports conversion to JSON format
var jsonData = JSON.parse(responseBody);
tests["Your test name"] = jsonData. value === 100;
Response time is less than 200ms to determine whether the request duration
is less than 200ms, and the specific duration is customized according to the situation
["Response time." is less than 200ms"] = responseTime < 200;
The above introduction is basically enough to complete the test of a single interface, but we know that without batch, scheduled tasks, then these will be meaningless, continue….
Collection
(batch) test
If you want to batch test and manage interfaces, then we need to save all the interfaces to be tested in the same collection (Collections), which you can think of as saving to the same folder. Let’s take a look at the steps in Postman:

Through the above steps, we get a set of interfaces to be tested, in order to simplify the situation, the condition for the success of each interface on my side is judged by whether the
code is 200 or not:
tests["Status code is 200" ] = responseCode.code === 200;
Once the batch
execution
is ready, we can start running the interface in bulk for testing:

After clicking Run, a new page will open:

-
Environment
: Used to switch the environment in which the interface runs, here is left alone, and Iteration will be talked about -
later
: Used to set the total number of times the interface will be run. -
Delay
: Sets the time interval between each run of the interface, in milliseconds. -
Data File
: Uploads the parameter data of the change of the test data file (discussed separately below
). We have seen how to make multiple interfaces run multiple times in a loop, but now there is a problem, according to the current step, the parameters of the interface are the same every time we run it, so even if we run it 100 times, 1000 times does not make much sense.
Let’s take a look at the interface we wrote for the login function:
class=”rich_pages wxw-img” src=”https://mmbiz.qpic.cn/mmbiz_png/eQPyBffYbufFVD73Mhn3G7uuOQXBddWqNvmfC2ULicoW8PtFA6llCMUVwShYb59ogW7HpGZHLpaqEIV1Qv4tMUA/640?wx_fmt=png”>
Use variables
Now the login account and password parameters are written dead, that is, how many times we execute, we are using this account to test.
So what if I want to test whether there are any abnormalities in other values used in the account password parameter? ( If you want to change it manually every time, you can skip this part / manual funny) Here we will briefly talk about how to use “variables” in Postman, as shown below:

syntax for referencing a variable :{{variable name
}}, As you can see in the figure, we set the parameter values of both the account and password fields to variables: {{username}}, {{
password}}
。 Of course, it is not possible to click Run (Send) after modification, because these two variables have not been assigned values yet, but we can assign them in the Pre-request Script panel: Pre-request
Script
Pre-request
Script is similar to Tests, except that scripts in Pre-request Script
run before the request is executed, while Tests The script in is executed after the request is completed. Therefore, we can use the script to assign values to the above two variables in the Pre-request Script
ribbon, such as:
setting the global variable
postman .setGlobalVariable("username", "test1");
postman.setGlobalVariable("password", "123456");
But using Pre-request Script
for assignment still doesn’t solve our problem, because according to this way of writing, no matter how many times it is run, it is actually tested with fixed (written) data. Of course, since it is a scripting language, there will be more flexible usage, so let’s not do it here.
,
we will talk about Data File, which is used to upload test data (file) to assign values to the corresponding variables before running the collection. Let’s take the test data in CSV format as an example:
222222test3, 123456test4, 444444
The data format is similar to a table, the first row represents the corresponding variable name, the next 4 lines represent 4 sets of account password data (two of which are correct data), we save a file with the above sample data suffix .csv
, start testing again to see the effect, we select the number of runs is 4 (corresponding to 4 sets of test data), select the corresponding CSV file after running, You can see that our results are indeed as we expected.
The result of the interface request run is two
successes and two failures, that is, each run is assigned a different account password test data (in the latest desktop client version, you can see the specific request situation of each time, I will not go into detail here).
If you use a JSON file, the format is as follows
:
[ { "username": "test1",
"password.] ": "123456" }, { "username": "test2",
"password": "222222" }, { "username": "test3",
"password": "123456" }, { "username": "test4",
"password": " 444444" }]
Periodic task Postman provides a Monitors function that allows us to submit a test task
to run at a set timer, such as every hour. The specific operation is as follows:
ensuring the order of interface calls
to pass the data returned by interface A to subsequent interfaces B, C, and D
interfaces for execution
First, to clarify, the interfaces mentioned next belong to the same collection by default.
Or take the interface collection we created above as an example, if you pay attention to the results of our batch testing, you will find that the execution order of the interfaces is actually in the order of the directory here (from top to bottom), that is: Request1
-> Request2
-> Request3
。

The interface name here may be a bit misleading, so again: execute in the order from top to bottom in the directory (not related to dictionary sorting), so
with this default execution order, then we can put the interface that needs to be executed first, such as the “login interface” in the first place.
Custom
execution
orderOf course, if there is only one default execution order, it usually cannot meet our complex business needs, so Postman provides us with a function: postman.setNextRequest(" Fill in the name
of the interface you want to jump”), support us to jump to the specified interface to continue execution, for example:
after we run the Request1 interface
successfully, we do not need to run Request2 but jump directly to Request3, then I can execute the jump code in the Tests ribbon of the Request1 interface, such as:

There
are a few points to note here:
-
postman.setNextRequest
() only takes effect when running the collection test, which means we run it separately (Send) When the interface Request1 is used, the function does not work. -
When we run the collection test successfully from
Request1
-> Request3, if there is an interface behindRequest3
, Then the subsequent interfaces will continue to execute in the default order, that is, the interface Request4 in the figure will still be executed. -
The specified jump interface must belong to the same collection.
-
The setNextRequest()
function, regardless of where it is called in the Tests script, is actually executed only at the end of the current script. For example, if we intermodulate the second line in the graph with the first line, the second line of code will still be executed after running the jump function.
So, using the setNextRequest()
function, we can conditionally skip unnecessary interfaces or create one of our own logical tests.
Before talking about data transfer, let’s talk about the use of global variables and environment switches in Postman.
The
concept of global variables is actually briefly mentioned in the previous article when we talked about Pre-request Script
, which means that we can set global variables through script code.
After running, the username
and password variables will be saved successfully, so we can use them in any interface through the syntax of variable references such as: {{username}}
.
In addition, Postman not only supports the way code sets global variables, it also supports visual operations:

enter the corresponding interface , you can manage it directly:
I created a host parameter in each environment, such as:
class=”rich_pages wxw-img” src=”https://mmbiz.qpic.cn/mmbiz_png/eQPyBffYbufFVD73Mhn3G7uuOQXBddWq6sz0DV8JfDqF6UhoHjHSqSibQ8ic0iaJMc7Yd7Nu3cib7HGjUdK9jZNq4Q/640?wx_fmt=png”
> of course, Our environment parameters can also be set by scripting the function as:
Note that this parameter is only added to the "parameter set" of the environment you currently select
postman.setEnvironmentVariable(" variable_key", "variable_value");
The use
of parameters in the “parameter set” of the switching environment is consistent with the global variables, as shown in {{host}}
in the figure, and the switching of different environments is shown in the following figure:

Resolve dependency issues
With the above preliminaries, let’s start looking at how to use Postman to solve dependency interface testing.
Assuming
that our interface Request1 is the login interface, a successful login will return a access_token
field as the identity (implemented). Then suppose that interface Request3 is an interface for placing orders, and you need to carry the access_token returned by login to access it normally.
Idea
< ul class="list-paddingleft-2" >
guarantee that Request1 is run before Request3
to return Request1 access_ The value of token is added to the environment variable Parameter Set.
Request3 referencing the value of access_token at request
time will return a value that exists in either a “global variable” or an “environment variable”, depending on the business situation, in which access_token
The value is environment-dependent, so choose to use the environment variable set storage here.
Operation 1 in
Postman
, Request1
interface in our directory has been guaranteed to execute first2
, Code situation of Tests in Request1
: if(responseCode.code === 200 && responseBody.has("access_token")){ If the code is 200
and the access_token keyword is present in the returned data, the login is considered successful
tests["login"] = true; Convert the returned content to json format, and take the access_token content, add it to the environment variable
var jsonData = JSONparse(responseBody); The
way the access_token values are taken depends on the specific json data structure
postman.setEnvironmentVariable("token",jsonData.result.access_token); Jump to the
Request3 interface
postman.setNextRequest("Request3") }else{
tests["login"] = false; If the login fails, you can choose to jump to the corresponding processing interface after the failure to test
postman.setNextRequest("Other Request")
}
3, and use a variable in interface Request3 token :

My side is to put the token in the header information, and the specific use method depends on the interface parameter rules.
Run
the
Run Collection test, the result is as we expect, Request1 and Request3 pass the test, Request2 is skipped, and Request4 is still executed.
end
public number (zhisheng ) reply to Face, ClickHouse, ES, Flink, Spring, Java, Kafka, Monitor keywords such as to view more articles corresponding to keywords.
like + Looking, less bugs 👇