The Practical Application of Mock in Interface Testing

1. About the mock test

1. Meaning and purpose

Mock test is to use a dummy object ( Mock object) to create a test method for testing.

2. Why do we need to conduct Mock test?

Mock is to solve the problem that it is difficult to develop and test due to coupling between different units. Therefore, Mock can appear not only in unit tests, but also in integration tests and system tests. The biggest function of Mock is to help you decompose the coupling of unit tests. If your code has dependencies on another class or interface, it can help you simulate these dependencies and help you verify the behavior of the called dependencies.
For example, a piece of code has such dependencies:
insert image description here
when we need to test class A, if there is no Mock, we need to build the entire dependency tree, and using Mock can decompose the structure, as follows:
insert image description here

3. Mock object applicable scenarios

It is necessary to separate the current unit under test from its dependent modules, construct an independent test environment, and not pay attention to the dependent objects of the unit under test, but only focus on the functional logic of the unit under test.

For example, the code under test needs to rely on the return value of the third-party interface for logic processing. Due to network or other environmental factors, the call to the third party is often interrupted or fails, and the unit under test cannot be tested. At this time, mock technology can be used to The unit under test and dependent modules are isolated so that testing can proceed.

The module that the unit under test depends on has not been developed yet, and the unit under test needs to rely on the return value of the module for subsequent processing.

① In the front-end and back-end projects, before the development of the back-end interface is completed, the interface is jointly debugged;

② The interface of the dependent upstream project has not been developed yet, and the joint debugging test of the interface is required;

The objects that the unit under test depends on are difficult to simulate or have complex structures.
For example, there are many abnormal conditions of Alipay payment, but simulating such abnormal conditions is complicated or impossible to simulate. For example, querying the order results of Juhuasuan cannot be simulated in the test environment.

4. Advantages of mock testing

1. Teams can work in parallel

With Mock, the front-end and back-end personnel only need to define the interface document to start working in parallel without affecting each other, and only communicate closely in the final joint debugging stage; if there is an interface coupling between the back-end and the back-end, it can also be mocked Solution; if the dependent interface is not ready during the test, Mock can also be used; there will be no situation where one team waits for another. In this way, the development self-test stage can be carried out early, so that the timing of finding defects is also advanced, which is conducive to the guarantee of the entire product quality and progress

2. Turn on the TDD mode, that is, test-driven development

Unit testing is the cornerstone of TDD implementation, and TDD often encounters the situation that the collaborative module has not been developed yet, but with mock, all these are not problems. After the interface is defined, the tester can create a Mock, add the interface to the automated test environment, and create tests in advance.

3. Can simulate those inaccessible resources

For example, if you need to call a resource outside the "wall" to facilitate your own debugging, you can mock one yourself.

4. Isolation system

If we need to call a post request, in order to obtain a certain response, to see if the current system can correctly process the returned "response", but this post request will cause data pollution in the database, then we can make full use of Mock to construct a virtual The post request, we just specify the return for him.

5. It can be used for demonstration

If we need to create a demonstration program and make a simple UI, we can also demonstrate it without developing back-end services at all. Speaking of demos, if you have already built a system and need to demonstrate it to customers, but there are some real data in it that you don't want users to see, then you can also use Mock interfaces to replace all these sensitive information interfaces.

6. Test coverage

If there is an interface with 100 different types of returns, we need to test whether the system can respond normally under different returns, but some returns will not occur under normal circumstances. For example, we need to test when the interface occurs 500 When an error occurs, whether the app crashes or not, don't tell me that you must do something to the server code to make it return 500. And using mock, all of this is easy to handle. You can simulate what you want to return, and you don't have to worry about my test coverage anymore!

5. Problems with mock testing

Using mock testing can sometimes improve the development efficiency of the team, but when both B and C have developed the code, the E2E test code should be changed from using mock testing to calling real modules to avoid missing integration between modules The problem. The problem with mocks mentioned here is mainly to prevent development and testing from overly relying on/believing in the mock interface.

A few points to keep in mind when using mocks:

Testers should not be fooled by E2E automated tests with high coverage. High coverage does not mean that there are no problems. Especially when taking over new projects, it is necessary to check whether mock tests are used in E2E tests, and further judge whether it is reasonable to use mock tests in these places, and whether these mock tests should be replaced by calls and integrations between real modules.

When the mock interface is replaced with an actual interface, the test/development must also redo the previous test.

ps: When you use the mock interface to improve efficiency, please note:

Your workload is actually twice as much as using the actual interface directly. If you are lazy during the test and replace it with the actual interface, it is just a simple test, then when the actual interface is different from the expected interface of the mock, the fault will meet you.

Suggestion: The mock interface can only be used for joint debugging of the main process/exception return test, and do not rely too much on the mock interface for testing.

After the test is completed, please make sure that the modification of the relevant code/configuration file for mocking has been completely restored before going online.
Suggestion: list items in the online checklist, and review before going online

2. Mock test method

1、Mock Server-Moco

This is a jar package, as long as the jar package is executed and the configuration file is specified, an http server can be started to provide services, and there is no need to restart the service after modifying the configuration file, and dynamic loading is supported. I'm using moco-runner-0.10.2-standalone.jar, run as follows:

```java -jar moco-runner-0.10.2-standalone.jar start -p 8080 -c XXX.json```
XXX.json就是我们的mock配置文件,比如:

[    

   {       

      "description": "api 1",        

      "request" :

          {            

             "method" : "get",        

             "uri" : "/foo"        

           },        

      "response": 
{            

      "json": {"foo":"bar"}        

      }    

   }

]

The above can be achieved. When we visit 127.0.0.0:8080/foo, a json is returned as {"foo":"bar"}.

2、fiddler

Everyone is familiar with fiddler. In the windows environment, you can customize the returned content at will, but a big disadvantage is that it is not cross-platform, and in many of our usual scenarios, we need to mock under Linux.

There are also some other mock tools, most of which achieve the purpose of mocking by writing js code or python, java and other codes, which will not be introduced here.

When choosing a mock tool, you can refer to the following aspects:
First, the data must be well managed, and don’t let me manage a bunch of files;
Second, the mock interface should be set to be exactly the same as the real interface, so that you only need to switch hosts You can switch between the mock
interface and the real interface without modifying the code;
●Third, cross-platform, the mock interface needs to be available under both Windows and Linux. As for cross-domain and dynamic loading, this is a necessary
condition.

3. Mock test example

Use Fiddler for Mock testing. This debugging method is suitable for rest interface debugging, web interface debugging, etc.

When test engineers do tests, they also need the server to return some special data for testing. Using the Fiddler AutoResponder
function to forge test data (create virtual objects) can greatly reduce the workload of test engineers.

1. The working principle of Fiddler AutoResponder
Using Fiddler can replace a [fake] HTTP response that is automatically returned, which is similar to using a breakpoint to modify the HTTP response, except that AutoResponder is automatic and the operation is more convenient. That is, the HTTP request sent by the browser did not reach the server, but was directly returned by Fiddler with a [fake] HTTP response.

2. Use Fiddler for mock testing

Interface packet capture ----- find the interface to mock
Take Nuggets homepage as an example, find the following interface https://gold-tag-ms.juejin.im/v1/categories

Copy the interface data to the local
Right-click on the interface, select save -> …and Open as Local File -> will be saved to the desktop by default, the data in the example is saved to test.json on the desktop

Modify data
Modify the json file saved locally. In the example, only the label data of the page is modified.

Replace the json file
Find the corresponding request in the web session panel, then drag it to the AutoResponder panel, click "Find a file..." in the RuleEditor, and select the path of the local json file.

Activate rules
Select "Enable rules" to activate the rules. Select "Unmatched requests passthrough" to pass unmatched HTTP requests.

save, refresh the page
Click the "Save" button. Just modify the json file saved locally, and then refresh the browser (or directly access the interface), you can see the effect.

Finally, I would like to thank everyone who has read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, if you can use it, you can take it away directly: [Collect at the end of the article]


     [The following is the most complete software test engineer learning knowledge architecture system diagram + full set of materials I compiled in 2023]


1. From entry to mastery of Python programming

2. Interface automation project actual combat

3. Actual Combat of Web Automation Project


4. Actual Combat of App Automation Project

5. Resume of first-tier manufacturers


6. Test and develop DevOps system

7. Commonly used automated testing tools


Eight, JMeter performance test

9. Summary (little surprise at the end)

life is long so add oil. Every effort will not be let down, as long as you persevere, there will be rewards in the end. Cherish your time and pursue your dreams. Don't forget the original intention, forge ahead. Your future is in your hands!

Life is short, time is precious, we cannot predict what will happen in the future, but we can grasp the present moment. Cherish every day and work hard to make yourself stronger and better. Firm belief, persistent pursuit, success will eventually belong to you!

Only by constantly challenging yourself can you constantly surpass yourself. Persist in pursuing your dreams and move forward bravely, and you will find that the process of struggle is so beautiful and worthwhile. Believe in yourself, you can do it!

Guess you like

Origin blog.csdn.net/NHB456789/article/details/132248499