0 Preface
This article is suitable for readers who have mastered Postman
the basic usage, that is, have a certain understanding of interface-related concepts, and have been able to use Postman
basic operations such as simulated requests.
Working environment and version:
- Windows 7 (64-bit)
- Postman (Chrome App v5.5.3)
PS Different versions of the page UI and the position of some functions will be a little different, but the impact is not significant.
First of all, let's think about it. If we want to achieve the effect of automated interface testing, what else needs to be done on the basic simulation request?
I roughly summarize it into 3 questions ( welcome to leave more supplementary suggestions in the comment area ):
1. How to judge whether the interface request is successful?
2. How to conduct batch and regular interface testing?
3. How to deal with dependent interface issues (for example, the interface for placing an order must require login first)?
Therefore, the following is mainly divided into 3 parts, introducing how to solve these 3 problems.
Here are 200G software testing tutorial materials for you, including use case templates, plan templates, report templates, performance tuning, automation tutorials, test templates, resume templates, interview skills, real test questions from Dachang, etc.! Click below to get it yourself:
1 Interface result judgment
First of all, since it is an automated test, we definitely need tools Postman
or codes to help us directly judge whether the results meet expectations. Then, in terms of interface testing, there are generally two ideas:
1. Determine whether the returned by the request code
meets expectations
2. Determine whether the content returned by the request contains the expected content (keywords)
Next, let's see how to use Postman
to solve the above problems:
1.1 Functional area
The relevant functions in Postman
are very conspicuous. Tests
The use of functions 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 consider the context and operating environment, that is to say, we only need to complete the code block of the result logic judgment here.
And it Postman
also provides us with some commonly used code templates in the ribbon Tests
on the right side of the panel , so it's not a big problem if you don't know much about . Code writing related will be introduced in detail below.SNIPPETS
JavaScript
1.2 Script related
First look at the code part of the above figure, we can find three variables responseCode
, responseBody
and (can be used directly):tests
responseCode
: Contains the status information returned by the request (such as: code).responseBody
: The data content returned by the interface request (the type is a string).tests
: In the form of a key-value pair, it is used to indicate whether our test result is successful or not, and is finally displayed inTest Results
.- key: (eg: code 200) We can use it as a description of the result.
- value: Its value is Boolean,
ture
indicating that the test passed,false
indicating that the test failed.
So the above code should not be difficult to understand, and with the returned result data and the way to indicate whether the result is successful or not, then our "interface result judgment" problem will be basically solved.
There are also a few more commonly used:
responseTime
: How long the request tookpostman
: You can do more, such as- Get the header information of the returned data:
`postman.getResponseHeader("")` - Set global variables:
`postman.setGlobalVariable("variable_key", "variable_value");`
- Get the header information of the returned data:
More functions can be viewed in the official documentation.
If you are a test worker, I have established a 2022 internal promotion group for the test opening of famous enterprises and large factories. Last year, 200+ students have been internally recommended to enter the large factory, and the highest annual salary has reached 70W+. Click below to enter the internal promotion channel:
1.3 Code Templates
Postman
The code templates provided for us in SNIPPETS
the functional area can already solve most of the situations. Let’s first select a few related to the result judgment to explain:
Status code : Code is 200
//根据返回的 Code 判断请求情况
tests["Status code is 200"] = responseCode.code === 200;
Response body: Contains string
//判断返回的内容中是否存在“关键字”。(tests 的 key 可修改,将不再强调)
tests["Body matches string"] = responseBody.has("这里可以改为你要判断的关键字内容");
//如上文提到的:
//判断结果中是否存在 access_token 关键字
tests["has access_token"] = responseBody.has("access_token");
Response body: is equal to string
//判断返回内容是否跟预期完全相等。
tests["Body is correct"] = responseBody === "这里可以改为你的预期内容";
Response body: JSON value check
//上文提到,responseBody 为字符串类型,支持转为 Json 格式
var jsonData = JSON.parse(responseBody);
tests["Your test name"] = jsonData.value === 100;
Response time is less than 200ms
//判断请求时长是否小于200ms ,具体时长按情况自定义
tests["Response time is less than 200ms"] = responseTime < 200;
The basics described above are enough to complete the test of a single interface, but we know that if there are no batch and scheduled tasks, then these will be meaningless, so continue...
2 Collection (batch) testing
If you want to perform batch testing and management of interfaces, then we need to save all the interfaces to be tested in the same collection (Collections)
, which you can think of as saving them in the same folder. First look at Postman
the steps in :
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 code
judged by whether it is 200:
tests["Status code is 200"] = responseCode.code === 200;
2.1 Batch execution
After the above is ready, we can start running the interface in batches for testing:
After clicking Run
, a new page will be opened:
Environment
: It is used to switch the environment in which the interface runs. I don’t care about it here, and I’ll talk about it later.Iteration
: Used to set the total number of times the interface will run.Delay
: Set the time interval between each run of the interface in milliseconds.Data File
: Upload the test data file (separately below)
2.2 Changing parameter data
We have already understood how to make multiple interfaces run repeatedly, but now there is a problem. According to the current step, the parameters of the interface are the same every time it is run, so even if we run it 100 times or 1000 times, it does not make much sense.
Let's take a look at the interface of a login function we wrote:
use variables
Now the login account and password parameters are hard-coded, that is, no matter how many times we execute it, we will use this account to test. So what if you want to test whether there is any abnormality in using other values for the account password parameter? (If you want to manually change it every time, you can skip this part/manually funny) Here we briefly talk about Postman
how to use "variables" in , as shown in the figure below:
The syntax for referencing a variable: {
{variable name}}, as you can see in the figure, we set the parameter values of the account and password fields as variables: {
{username}} 、{
{password}}
. (Send)
It is of course impossible to directly click to run after modification , because these two variables have not been assigned yet, but we can Pre-request Script
perform assignment operations in the panel:
Pre-request Script
Pre-request Script
Similar to Tests
, except that Pre-request Script
scripts in are run before the request is executed, while Tests
scripts in are executed after the request completes. Therefore, we can Pre-request Script
use the script to assign values to the above two variables in the functional area, such as:
//设置全局变量
postman.setGlobalVariable("username", "test1");
postman.setGlobalVariable("password", "123456");
But using Pre-request Script
the assignment operation still can't solve our problem, because according to this writing method, no matter how many times it is run, it still uses fixed (hard-coded) data for testing. Of course, since it is a scripting language, there will be more flexible usage, so I won't discuss it here.
test data set
Next, we will talk about Data File
that this option before running the collection is used to upload test data (files) to assign to the corresponding variables. Let's take CSV
the test data in the format as an example:
username,password
test1,123456
test2,222222
test3,123456
test4,444444
The data format is similar to a table. The first line represents the corresponding variable name, and the following 4 lines represent 4 sets of account password data (two of which are correct data). After we save a file with the content of the above sample data and the suffix name, we start testing again to see the effect. We choose the number of runs to be 4 (corresponding to 4 sets of test data), and after selecting the corresponding file to run, we can see that our results are indeed as we .csv
expected CSV
. The result of the interface Request
running is two successes and two failures, that is, the test data of different account passwords are assigned to each run (in the latest desktop client version, you can see the specific request status of each request, so I won’t go into details here).
If using Json
a file, the format is as follows:
[
{
"username": "test1",
"password": "123456"
},
{
"username": "test2",
"password": "222222"
},
{
"username": "test3",
"password": "123456"
},
{
"username": "test4",
"password": "444444"
}
]
2.3 Regular tasks
Postman
Provides a Monitors
(monitor) function that allows us to submit a test task and run it according to the set timer, such as testing once an hour. The specific operations are as follows:
3 Request dependency issues
After talking about the interface result judgment and collection batch test, let's look at the more complicated situation, that is, the dependent request problem. For example, our shopping order interface requires login before it can be accessed. But most of the dependency problem is actually a problem of data transfer between interfaces. For example, after calling the login interface, an identifier is returned. If it is, then when token
we request the order interface, we only token
need to carry the parameter along with the request. So, the problem becomes:
- Guaranteed interface call sequence
- Pass the data returned by interface A to subsequent interfaces B, C, and D
3.1 Interface Execution Sequence
First of all, let me explain that the interfaces mentioned next belong to the same collection by default (Collections)
.
Still 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 accordance with the order in the directory here (from top to bottom), namely: Request1 -> Request2 -> Request3
.
The interface name here may be a bit misleading, so I want to emphasize it again: execute in 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, for example, put the "login interface" first.
3.1.2 Custom execution order
Of course, if there is only one default execution sequence, it usually cannot meet our complex business needs, so Postman
provides us with a function: postman.setNextRequest("填写你要跳转的接口名")
, which supports us to jump to the specified interface to continue execution, for example:
After we successfully run Request1
the interface, we don’t need to run again Request2
but jump directly to it Request3
, then I can execute the jump code in the functional area Request1
of the interface , such as:Tests
Here are a few points to note:
1. postman.setNextRequest()
It only takes effect when running a collection test, that is to say, when we run (Send)
the interface alone Request1
, the function does not work.
2. After we run the collection test successfully from Request1 -> Request3
, if Request3
there is an interface after , then the subsequent interfaces will continue to be executed in the default order, that is, the interface in the figure Request4
will still be executed.
3. The specified jump interface must belong to the same set.
4. setNextRequest()
No matter where the function Tests
is called in the script, it is only actually executed at the end of the current script. For example, if we intermodulate the second line with the first line in the figure, the second line of code will still be executed after running the jump function.
So, using setNextRequest()
the function, we can skip unnecessary interfaces according to the condition, or build a logic test of our own.
3.2 Data transfer
Before talking about data transfer, let's talk about Postman
the use of global variables and environment switching in .
3.2.1 Global variables
Pre-request Script
The concept of global variables is actually briefly mentioned in the above , that is to say, we can set global variables through script code, and we can see the effect after running the above script:
We can see that after running, the two variables of username
and have been successfully saved, then we can use them password
in any interface through the syntax of variable references such as: .{
{username}}
In addition, Postman
it not only supports the way of setting global variables in code, but also supports visual operations:
After entering the corresponding interface, you can directly manage:
3.2.2 Multi-environment distinction and switching
Usually, our interfaces are divided into test version and online version (or more), and their difference may only be ULR
different, so global variables are not suitable to solve this problem.
Creation of parameters
You may have noticed that in the figure above, I have created several parameter "collections" for different environments. Let's take a look again:
I created a parameter in each environment host
like:
Of course, our environment parameters can also be set through scripts, the function is:
//注意,该参数只添加到你当前选择的环境的“参数集”中
postman.setEnvironmentVariable("variable_key", "variable_value");
Use and switch
The use of parameters in the environment "parameter set" is consistent with the global variables, as shown in the figure {
{host}}
, the switching between different environments is shown in the figure below:
3.3 Solving dependency problems
After mastering the above preliminary knowledge, let's start to see how to use it to Postman
solve the interface test with dependencies.
hypothetical scenario
Our interface Request1
is the login interface, and a successful login will return a access_token
field as an identifier (implemented). Then assume that the interface Request3
is an interface for placing an order, which needs to be returned with the login access_token
to access normally.
train of thought
1. Guaranteed to be run before Request1
2. Add the value returned by to the environment variable "parameter set". 3. Quote the value of when requestingRequest3
Request1
access_token
Request3
access_token
Store the return value in the "global variable" or "environment variable", depending on the specific business situation, the
access_token
value in this example is related to the environment, so here we choose to use the environment variable set to store.
Operations in Postman
1. The code in 2. has been guaranteed Request1
to be executed first in our catalog :Request1
Tests
if(responseCode.code === 200 && responseBody.has("access_token")){
//如果 code 为 200, 并且返回的数据中存在 access_token 关键字,则认为登录成功
tests["login"] = true;
//将返回的内容转为 json 格式,并且取到 access_token 内容,添加到环境变量中
var jsonData = JSON.parse(responseBody);
//access_token的取值方式视具体的 json 数据结构而定
postman.setEnvironmentVariable("token",jsonData.result.access_token);
//跳转到 Request3 接口
postman.setNextRequest("Request3")
}else{
tests["login"] = false;
//登录失败,可以选择跳转到对应失败后的处理接口进行测试
//postman.setNextRequest("Other Request")
}
3. Request3
Use variables in the interface token
:
> 我这边是将 `token` 放在头部信息中, 具体使用方式时接口参数规则而定。
run and see the result
Running the collection tests, we can see that our results are in line with our expectations, Request1
and Request3
the tests passed, Request2
skipped, and Request4
still executed. Done…