Can the test report be submitted after the development is completed? An easy-to-complete interface automation testing guide!

Application Scenario

The development has not been completed yet, these are the verifications on the service, how to synchronize the tests? As soon as the server is configured, the test is required to submit a report. Is it overtime?

Testing seems to be post-work. Only after the version is developed or the server is set up can the real action be taken. And often at this stage, the date for the system (program) to go online has also arrived. It’s really not necessary to do it in the early stage, but it’s exhausting in the later stage.

This time we use some tools (MockServer, rest Assured) to implement forward-looking API (interface) testing before the server is started. And when the real server starts, you only need to connect the test code to the real server to run.

Reminder: If you want to follow the example, please be sure to configure the following tools.

The use case is mainly to combine the basic functions of rest-Assured and MockServer to do pre-automated API testing. For those who don’t know rest-Assured, please do some extra homework (you can refer to the rest-Assured article I wrote before , There are detailed configuration and application steps, and MockServer also has basic articles ).

  • IDE: IntelliJ IDEA

  • Language: Java

  • API Test Development: Rest-Assured

  • API server: MockServer

  • Test framework: TestNg

  • Project Type: Maven

knowledge focus

MockServer application: verify the request received by the server

rest Assured: Simulate API requests

Maven project configuration

Configure MockServer, rest-Assured in POM.xml.

As shown in the figure below: MockServer and rest-Assured need to be correctly introduced into the <dependency> node of pom.xml.

Tip: If the dependency is not loaded automatically, you can manually load it, and the corresponding jar package will be downloaded.

MockServer:

picture

rest-Assured:

picture

Test case decomposition

test case

The following use case description should be familiar. It is a typical BDD description. Here I write the parameters and verification request together for the convenience of this explanation. The real environment can separate the data from the scene, which will be clearer.

Given: the API server is running

When: The server receives a request from the API (api address: http://localhost:10800/testing.retry/{id})

And: The parameter is "?testParameter=false"

And:(header)头字段:headerId="id"; headerVersion="version"; headerName="name"

Then: Verify that the server received the correct request

Example: times: 1,

(header)头字段:headerId="id"; headerVersion="version"; headerName="name"

Parameter: "?testParameter=false"

And: Verify server response code (200)

use case analysis

First, build a server that accepts the API and can respond with a 200 to eligible API requests.

Address: http://localhost:10800/testing.retry/{id}

Parameters: ?testParameter=false

(header)头字段:headerId = "id"; headerVersion = "version"; headerName = "name";

When the server receives the request, it needs to verify that the server received the correct request, and the number of requests is 1, and returns 200.

1. The code response can be verified by rest-Assured.

2. The data received by the server is verified by MockSever.

With the above understanding, now is the implementation steps:

1. API server - MockServer.

2. Create API response expectations (Active Expectations) - MockServer.

3. Simulate the request – rest-Assured and verify the return status.

4. Verify the number of requests, parameters, header fields - MockServer.

5. Close MockerServer.

Tip: This step is very important to make subsequent tests organized and to organize the test code systematically and logically.

TestNg use case script

According to the above analysis, let us look at the implementation of the code step by step.

Tip: This example uses Java + Maven + testNg (if you are a little unfamiliar with this combination, you can read my related basic articles ).

The complete test script is shown in the image below.

picture

Detailed code

1. Global parameters

We can define shared information as variables, and the scope of the application considered can be defined as local variables or global variables.

What should I do if I can't determine which defines local variables or global variables?

Hint: This problem is encountered when starting to write test code, even an experienced person will have the same problem. Don't worry about this, usually I will write it as a local variable first, or write it as a fixed variable without defining the variable. In the end, when the code of a use case is written completely, it will be clear at a glance when checking the code that local variables or global variables are defined.

String headerId = "id";
String headerVersion = "version";
String headerName = "name";
String queryParameter = "testParameter";
String queryParameterValue = "false";
String baseURI = "http://localhost:10800";
int requestTime = 1;
private ClientAndServer mockServer;

2. API Server - Mock Server

As shown in the picture: we first create a method startMockServer(), this method is to start a MockServer port 10800. The default address is this machine: http://localhost:10800. The MockServer variable is called by other methods. Global variables are defined here.

private void startMockServer() {
    mockServer = startClientAndServer(10800);
}

3. Create API response expectations (Active Expectations) - MockServer

As analyzed above, we need the API server to respond with 200 to the following requests.

Note: The {id} of the request address is a variable, and the variable pathId is parameterized in the code

The mockServerActiveExpectations () method starts the API server and creates API response expectations (Active Expectations).

Address: http://localhost:10800/testing.retry/{id}

Parameters: ?testParameter=false

(header)头字段:headerId = "id"; headerVersion = "version"; headerName="name"

picture

The mockServerActiveExpectations() application:

startMockerServer() starts the API server http://localhost:10800.

The code mockServer.when(request().withPath.... is to create an Active Expectations, these are standard MockServer syntax, don't worry about not understanding, just try it out.

picture

4. Mock request – rest-Assured, verification response code 200

picture

This is the syntax of rest-Assured. Simply put, it simulates the user's behavior and sends an api request to the server http://localhost:10800/.

Note: The header (header field) is all test data, and all use "test".

log().all : Just for debugging, it can be removed or kept later.

5. Verify the number of requests, parameters, header fields - MockServer

picture

In order to make the code concise and easy to read, and at the same time have reusability, here is a separate verification method.

verifyReceivedRequestDataAndTimes(), through the code, we can see that the path, parameters, methods, specific data of the header field and the number of requests received will be verified here.

Don't worry, these are MockServer syntax too.

picture

6. Close the mocker server

Don't forget, this step is also critical. The test environment is very important, especially when you have a set of test cases. The troubles caused by not cleaning up the environment are countless.

picture

picture

use case run

Ok, let's test the results first. Here I run it directly in the IDE.

Open the dashboard of MockerSever at the same time: http://localhost:10800/mockserver/dashboard

Tips: The code runs very fast. In order to capture the dashboard records, add a 20-second waiting time before the code closes MockerSever.

picture

For those who don’t understand how to view this dashboard, you can refer to my previous article on MockServer configuration and construction for a detailed introduction.

picture

The figure below shows the verification result of the request by MockerSever.

1. Details of the verification request;

2. Number of authentication requests.

picture

The data of the API request simulated by rest-Assured can be viewed in the running code log, as shown in the following figure:

picture

Error checking and code optimization

Now we do some negative tests to verify that this use case can catch bugs under the "wrong" request and expectation.

We verify that the API server received 2 requests

picture

After running the code, we will get the following error. We expected the server to receive 2 requests, but actually received 1 request, so the error reported that no matching 2 requests were found.

picture

Click click to see difference, the right side of the new window shows the actual request received by the server (only once). Other differences can be ignored as there is no validation here.

picture

Based on this change, if you view the dashboard, you cannot see the verification information. The validation code fails and the entire script stops.

So we improve verifyReceivedRequestDataAndTimes() and add try ...catch..

Note: This method is changed to return a Boolean value, because we need this Boolean value to verify the success and failure of the test case. Otherwise, the test validation shows a failure, but the test case runs successfully. See SoftAssert described below.

picture

Run the code again: the dashboard can display the verification failure information.

picture

The verification method adds SoftAssert, so that the code encounters a verification failure and continues to execute. Also add assertAll() at the end. This way, the validation fails and the use case fails.

picture

In order to be able to check where the error is at a glance in the running result, improve try..catch.. to print out the error (here I use print, and it is recommended to use Log in the real environment). In this way, it is realized that the verification fails, the use case fails, and the reason for the failure.

picture

We verify that the header does not match

For example, we expect the request headerId value to be "ID", but the request received by the server is "test".

picture

The verification failure results are as follows:

picture

Summarize

Well, this completes how to put an elephant in the refrigerator, not difficult!

When the real server is online, you only need to point the rest-Assured request to the real test server, and comment the MockServer, even if the boss wants to report on the same day, we can deliver it.

The above is to be an introduction. The most important thing is to use various types of testing tools to meet your own testing needs. All the big testers can apply it flexibly and draw inferences from one instance.

Finally: The complete software testing video tutorial below has been sorted out and uploaded, and friends who need it can get it by themselves [Guaranteed 100% free]

Software Testing Interview Documentation

We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Ali, Tencent, and Byte, and some Byte bosses have given authoritative answers. Finish this set The interview materials believe that everyone can find a satisfactory job.

おすすめ

転載: blog.csdn.net/wx17343624830/article/details/132669691