Postman automated interface testing

This article is intended for those who have already mastered the basic usage of Postman, that is, have some understanding of interface concepts and are already familiar with using Postman to simulate requests.

Current Environment:

  • Window 7 – 64
  • Postman Version (free) : Chrome App V5.5.3

The UI and location of some functions may be slightly different from version to version, but the impact is minor.

Let’s start by thinking about what else we need to do on basic mock requests if we want to achieve automated interface testing.

I can roughly summarize the following three questions (more comments and suggestions are welcome) :

  • How do I determine whether an interface request is successful
  • How do I perform batch and periodic interface tests
  • How to deal with interface dependency issues (for example, the interface for ordering goods must be logged in first)

Therefore, the following is mainly divided into three parts for introduction, in order to solve the three problems respectively.

Interface result judgment

First, since it’s an automated test, we definitely need tools (Postman) or code that can help us directly determine whether the results are as expected. So in the interface test, there are basically two ideas:

  • Determine if the code returned by the request meets expectations
  • Determine if the content returned by the request contains the expected content (keyword)

Let’s look at how Postman can be used to solve these problems:

Functional areas

One of the most obvious things about Postman is that using Tests requires a certain level of programming language background, and JavaScript is currently supported. But the nice thing is that we don’t need to worry about the context or the runtime environment anymore, which means we just need to complete the code block of the resulting logic here.

Postman also provides some common code templates in the SNIPPETS function area on the right side of the Tests panel, so it’s not a problem if you don’t know much about JavaScript. More on coding is covered below.

The script associated

The responseCode, responseBody, and tests variables can be used directly:

  • responseCode: contains the status information returned by the request (e.g. Code)
  • responseBody: Data content requested back for the interface (type string)
  • tests: is the form of key-value pair, which is used to indicate whether our Test result is successful or not, and is finally displayed in Test Results.
  • key(e.g. Code 200) we can use as a description of the result
  • value: The value is a Boolean, true indicates that the test passes, false indicates that the test fails.

So the above code should be easy to understand, and with the data to return the results and the way to indicate their success, our “interface result judgment” problem is basically solved.

Here are some examples:

  • ResponseTime: Indicates how long the request takes

  • Postman: You can do more, like

    • Get the header information for the returned data:postman.getResponseHeader("")
    • Set global variables:postman.setGlobalVariable("variable_key", "variable_value");

The code template

Postman has provided us with code templates in SNIPPETS for the most part. Here are a few that are relevant to judging results:

Status code : Code is 200

// Test ["Status Code is 200"] = responsecode. Code === 200;Copy the code

Response body: Contains string

// Determine whether the returned content contains a keyword. Tests ["Body matches String "] = responseBody.has(); Access_token tests["has access_token"] = responseBody.has("access_token");Copy the code

Response body: is equal to string

// Determine if the content returned is exactly the same as expected. Tests ["Body is correct"] = responseBody === ";Copy the code

Response body: JSON value check

Parse (responseBody) var jsonData = json.parse (responseBody); tests["Your test name"] = jsonData.value === 100;Copy the code

Response time is less than 200ms

If tests["Response time is less than 200ms"] = responseTime < 200; if tests["Response time is less than 200ms"] = responseTime < 200; if tests["Response time is less than 200ms"] = responseTime < 200;Copy the code

This is pretty much enough for testing a single interface, but we know that without batch, scheduled tasks, it would be meaningless. Move on…

Set (batch) tests

To batch test and manage interfaces, we need to store all of the interfaces to be tested in the same Collections, you can think of it as the same folder. 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 success condition of each interface on my side is judged by whether the code is 200:

tests["Status code is 200"] = responseCode.code === 200;
Copy the code

Batch execution

With the above in place, we can start batching interfaces to test:

After clicking Run, a new page will open:

  • Environment: Used to switch the environment in which the interface runs
  • Iteration: Sets the total number of times the interface will run.
  • Delay: Sets the interval between running interfaces, in milliseconds.
  • Data File: Upload test data files (described separately below)

Variable parameter data

We have seen how to run multiple interfaces multiple times, but the problem is that at this stage, the interface parameters are the same every time we run it, so it doesn’t matter if we run it 100 times or 1000 times.

Spring Boot: github.com/javastacks/…

Let’s take a look at the interface we have written for the login function:

Use the variable

Now login account and password parameters are written dead, that is, but we execute how many times, is to take this account to test.

So what if you want to test for exceptions using other values for your account password parameter? (You can skip this section if you want to change it manually every time.) Here’s a quick look at how to use “variables” in Postman:

{{username}}, {{password}}, {{username}}, {{password}}, {{username}}, {{password}}. This is not possible because the variables have not been assigned yet, but we can assign them in the pre-Request Script panel:

Pre-request Script

The pre-Request Script is similar to Tests except that the Tests Script is run before the request is executed, while the Tests Script is run after the request is completed. Therefore, we can use the Script to assign the first two variables in the pre-Request Script function area, such as:

/ / set the global variable postman. SetGlobalVariable (" username ", "test1"); postman.setGlobalVariable("password", "123456");Copy the code

But using the pre-Request Script for assignment still doesn’t solve our problem, because no matter how many times we run it, we’re still testing with fixed (dead) data. Of course, since it is a scripting language, there will be more flexible usage, here will not be.

Test data set

Next, we’ll talk about Data File, which is used to upload test Data (files) to assign values to variables before running the collection. Let’s take the test data in CSV format as an example:

Username,password test1,123456 test2,222222 test3,123456 test4,444444Copy the code

The data format is similar to the table, the first line represents the corresponding variable name, and the following four lines represent the four groups of account and password data (two of which are correct data). After saving a file containing the above sample data with the suffix.csv, we start testing again to see the effect. After choosing 4 runs (for 4 sets of test data) and selecting the corresponding CSV file to run, we can see that our results are indeed as expected.

The result of the interface Request run is two successes and two failures, that is, each run assigned with a different account password test data (in the latest version of the desktop client can see the specific situation of each Request, I won’t go into details here).

If you use Json files, the format is as follows:

[
  {
    "username": "test1",
    "password": "123456"
  },
  {
    "username": "test2",
    "password": "222222"
  },
  {
    "username": "test3",
    "password": "123456"
  },
  {
    "username": "test4",
    "password": "444444"
  }
]
Copy the code

Regular task

Postman Monitors a test task by submitting it to a timer (for example, once an hour).

Request dependency problem

After talking about interface result judgment and set batch testing, let’s take a look at the more complex case of dependency request problems, such as our shopping order interface requiring login before access. However, most of the dependency problem is essentially a problem of data transmission between interfaces. For example, when the login interface is called, an identifier is returned, assuming that it is token, so we can request the interface to place an order with token parameters. So, the question becomes:

  • Ensure the sequence of interface calls
  • The data returned by interface A is passed to subsequent interfaces B, C, and D

Interface execution sequence

First, to clarify, the following interfaces all belong to the same collection by default.

If you look at the results of our batch test, you will see that the interface is executed in the order (top to bottom) : Request1 -> Request2 -> Request3.

The interface name may be a bit misleading, so again: execute from top to bottom in the directory (regardless of dictionary sort)

So with this default order, we can put the interface that needs to be executed first, such as “login interface” first.

Customize the execution sequence

Postman provides a function called postman.setNextrequest (” Enter the name of the interface you want to jump to “) that allows you to jump to the specified interface and continue executing. For example:

In the Tests section of the Request1 interface, I can skip to the Tests section of the Request1 interface instead of running the Tests section of the Request2 interface.

A few things to note here:

  • postman.setNextRequest()This only works when running a collection test, i.e. when we run Request1 (Send) separately, the function does not work.
  • When we run the collection test successfully fromRequest1 -> Request3After that, if there are interfaces following Request3, the subsequent interfaces continue to be executed in the default order, i.e., the interface Request4 in the figure will still be executed.
  • The specified jump interface must belong to the same collection.
  • setNextRequest()No matter where the function is called in the Tests script, it is actually executed only at the end of the current script. For example, if we intercall the second line of the diagram with the first line, the second line will still be executed after the jump function is run.

So, using the setNextRequest() function, we can either conditionally skip unnecessary interfaces or build our own logic test.

The data transfer

Before we talk about data transfer, let’s talk about the use of global variables and environment switches in Postman.

The global variable

The concept of global variables was mentioned briefly when we talked about pre-Request Script, which means that we can set global variables through Script code.

The username and password variables are successfully saved and can be used in any interface using variable reference syntax such as {{username}}.

In addition, Postman not only supports the way code sets global variables, it also supports visual operations:

After entering the corresponding interface, you can directly manage:

Multi-environment differentiation and switching

Often, our interfaces are divided into test and online versions (or more), and the only difference between them may be the ULR, so global variables are not suitable to solve this problem.

Parameter creation

As you may have noticed, I have built several parameter “sets” for different environments in the figure above. Take a look:

I created a host parameter in each environment, such as:

Of course, our environment parameters can also be set by script, function:

/ / note that the parameters of the currently selected environment only to add to your "parameter set" postman. The setEnvironmentVariable (" variable_key ", "variable_value");Copy the code

Use and switch

The parameters in the “parameter set” environment are used in the same way as global variables, as shown in the figure {{host}}. See the following figure for switching between different environments:

Resolving dependencies

With that in mind, let’s look at how to use Postman to solve interface tests with dependencies.

What-if scenarios

Our interface Request1 is the login interface, and a successful login will return an access_token field as an identifier (implemented). Suppose the interface Request3 is an order placing interface that needs to carry the access_token returned by the login.

Train of thought

  • Ensure that Request1 is run before Request3
  • Add the value of access_token returned by Request1 to the environment variable “Parameter set”.
  • Request3 references the value of access_token at request time

The returned value is stored in Global variable or Environment variable, depending on the service situation. In this example, the value of access_token is environment-dependent, so the environment variable set is used here.

Operations in Postman

1. The Request1 interface in our directory is guaranteed to be executed first

The Tests code in Request1 is as follows:

If (responseCode. Code = = = 200 && responseBody) from the (" access_token ")) {/ / if the code is 200, and the returned data exist in the access_token key words, Tests ["login"] = true; Var jsonData = json.parse (responseBody); var jsonData = json.parse (responseBody); / / access_token value way depending on the specific json data structure postman. The setEnvironmentVariable (" token ", jsonData. Result. Access_token); Postman.setnextrequest ("Request3")}else{tests["login"] = false; // postman.setNextrequest ("Other Request")}Copy the code

Select * from Request3;

I put the token in the header information, and the specific usage depends on the interface parameters.

run

Run the collection test, the results are as expected, Request1 and Request3 pass the test, Request2 is skipped, and Request4 is still executed.

Original link: blog.csdn.net/cai_iac/art…

Copyright notice: This article is originally published BY CSDN blogger “Wiky”. It follows CC 4.0 BY-SA copyright agreement. Please attach the link of the original source and this statement.

Recent hot articles recommended:

1.1,000+ Java Interview Questions and Answers (2021)

2. Don’t use if/ else on full screen again, try strategy mode, it smells good!!

3. Oh, my gosh! What new syntax is xx ≠ null in Java?

4.Spring Boot 2.5 is a blockbuster release, and dark mode is exploding!

5. “Java Development Manual (Songshan version)” the latest release, quick download!

Feel good, don’t forget to click on + forward oh!