Mock for interface automation testing

[Software Testing Interview Crash Course] How to force yourself to finish the software testing eight-part essay tutorial in one week. After finishing the interview, you will be stable. You can also be a high-paying software testing engineer (automated testing)

1. Mock implementation principle and implementation mechanism

At some point, when the backend is developing the interface, the processing logic is very complicated. When testing, how should the backend test without completing the interface?

We need to test, but some requests need to modify the parameters, or change the way the request is implemented, such as modifying the status code , replacing the generated pictures, or replacing the execution file, etc. 

Introduction to Mock

The word Mock means simulation in English, so we can guess that the main function of this library is to simulate something. To be precise, Mock is a library in Python used to support unit testing. Its main function is to use mock objects to replace specified Python objects to simulate the behavior of objects.

During the unit testing process of the project, you will encounter:

1. Interface dependency

2. External interface call

3. The test environment is very complex

Unit tests should only test the current unit. All internal or external dependencies should be stable and have been tested elsewhere. Using mocks, you can simulate and replace the implementation of external dependent components, so that the unit test will Focus is only on the current unit function.

Resolve test dependencies

For example, we want to test module A, and then module A depends on the call of module B. However, due to changes in module B, the results returned by module A are changed, causing the test case of module A to fail. In fact, there is no change for module A and the use cases of module A, so it should not fail.

This is when mock comes into play. Use mock to simulate the part that affects module A (module B). As for the mocked part (module B), it should be tested by other use cases.

example

import requests
from unittest import mock
 
def request_lemonfix():
    """
    :return:
    """
    res = requests.get('http://www.baidu.com')
    return res.status_code.encode('utf-8')
 
 
if __name__ == '__main__':
    request_lemonfix = mock.Mock(return_value="我已经替换了数据")
    print(request_lemonfix())
    
结果:
我已经替换了数据
    ```
 
2. Simple case implementation of mock
  • basic skills
# function.py
def multiply(x, y):
return x * y
 
def add_and_multiply(x, y):
    addition = x + y
    multiple = multiply(x, y) # 回调函数
    return (addition, multiple)
  • Write test cases for the add_and_multiply() function
import mock
import requests
import unittest
 
url = "www.baidu.com/login"
data = {
    "user_id": "001",
    "password": "caichen"
}
 
 
def post_request(url, data):
    """登陆百度账号"""
    res = requests.post(url, data).json()
    return res
 
 
class TestLogin(unittest.TestCase):
    """单元测试"""
    def setUp(self) -> None:
        print("case开始执行")
 
    def tearDown(self) -> None:
        print("case执行结束")
 
    def test_01(self):
        """模拟数据判断是否正确"""
        url = "www.baidu.com/login/tieba"
        data = {
            "user_id": "001"
        }
        sucess_test = mock.Mock(return_value=data)
        post_request = sucess_test
        res = post_request
        self.assertEqual("654321", res())
        # self.assertEqual({'user_id': '001'},res())
 
 
if __name__ == '__main__':
    unittest.main()
 
# 错误结果
F
case开始执行
======================================================================
case执行结束
FAIL: test_01 (__main__.TestLogin)
模拟数据判断是否正确
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:/Users/x1c/Desktop/untitled/mocktest.py", line 35, in test_01
    self.assertEqual("654321", res())
AssertionError: '654321' != {'user_id': '001'}
 
----------------------------------------------------------------------
Ran 1 test in 0.001s
 
FAILED (failures=1)
 
# 正常结果
case开始执行
.
case执行结束
----------------------------------------------------------------------
Ran 1 test in 0.000s
 
OK
 
 
3.mock implements get data simulation
举个例子来说:我们有一个简单的客户端实现,用来访问一个URL,当访问正常时,需要返回状态码200,不正常时,需要返回状态码404。首先,我们的客户端代码实现如下:
 
```
import requests
 
 
def send_request(url):
    r = requests.get(url)
    return r.status_code
 
 
def visit_ustack():
    return send_request('http://www.ustack.com')
```
 
# 外部模块调用visit_ustack()来访问baidu的官网。下面我们使用mock对象在单元测试中分别测试访问正常和访问不正常的情况。
```
import unittest
import mock
import client
 
 
class TestClient(unittest.TestCase):
 
def test_success_request(self):
    success_send = mock.Mock(return_value='200')
    client.send_request = success_send
    self.assertEqual(client.visit_ustack(), '200')
 
def test_fail_request(self):
    fail_send = mock.Mock(return_value='404')
    client.send_request = fail_send
    self.assertEqual(client.visit_ustack(), '404')
    
```

1. Find the object to be replaced: What we need to test is the visit_ustack function, then we need to replace the send_request function.

2. Instantiate the Mock class to get a mock object, and set the behavior of this mock object. In a successful test, we set the return value of the mock object to the string "200", and in a failed test, we set the return value of the mock object to the string "404".

3. Use this mock object to replace the object we want to replace. We replaced client.send_request

4. Write test code. We call client.visit_ustack() and expect its return value to be the same as our default.

The above are the basic steps for using mock objects. In the above example, we replaced the object of the module we wrote. In fact, we can also replace the objects of the standard library and third-party modules. The method is the same: import it first, and then replace the specified object.

4. The difference between Mock and mockrunner
Mockrunner is used for simulation testing of applications in the J2EE environment. Not only does it support Struts actions, servlets, filters and tag classes, it also includes a JDBC and a JMS testing framework that can be used to test EJB-based applications.

Mockrunner extends JUnit and simulates the necessary behavior without calling the actual infrastructure. It does not require a running application server or database. Additionally, it does not call the web container or Struts ActionServlet. It is very fast and allows the user to manipulate all involved classes and mock objects during all steps of the test. It can be used to write very complex unit tests for J2EE based applications without incurring any overhead. Mockrunner does not support any kind of in-container testing.

Mockrunner does not read any configuration files such as web.xml or struts-config.xml. You can specify all parameters using the Mockrunner API. Therefore, servlets, filters, tags and Struts actions can be tested as reusable components, regardless of the setup you use in one or another application. Unable to test definitions in configuration file. If you want to do this, you can use StrutsTestCase for Struts-based applications or Cactus.

Mockrunner supports Java versions from 1.3 to 1.6 as well as J2EE 1.3, J2EE 1.4 and JavaEE5. EJB 3.0 is not supported yet. Mockrunner supports Struts versions 1.1, 1.2 and 1.3.

Download address: Mockrunner download | SourceForge.net

mockrunner must configure the java environment

Start using the command: java -jar moco-runner-0.12.0-standalone.jar http -p 8801 -c config.json

Configure the config.json file to mock data

[
{
"response" :
  {
    "text" : "Hello, Moco"
  }
}
]
    ```
 
使用命令启动:
java -jar moco-runner-0.12.0-standalone.jar http -p 8801 -c config.json
访问http://localhost:8801
就会显示 Hello, Moco
 

MockRunner works by building a complex linking rule

[
{
"request":{
    "uri":"/monitorApplication/alert/confirm",
    "method":"PUT",
    "text":"{\"id\":\"123\"}"
},
"response":{
    "status":200,
    "json":{
        "code":"0",
        "msg":"OK!",
        "data":null
    }
}
}
]
5.Interface testing basic interview
  • How to do interface testing in the project?

    Use testing tools to verify parameters, request parameters, and return parameters

  • How to write cases during interface development

    Rule documents are familiar with the mock verification format

  • How to understand Mock

    Simulate return parameters, simulate interface

  • Mock running at work?

    Help front-end achieve normal development

The following are supporting learning materials. For those who are doing [software testing], it should be the most comprehensive and complete preparation warehouse. This warehouse has also accompanied me through the most difficult journey. I hope it can also help you!

Software testing interview applet

A software test question bank that has been used by millions of people! ! ! Who is who knows! ! ! The most comprehensive interview test mini program on the Internet, you can use your mobile phone to answer questions, take the subway, bus, and roll it up!

Covers the following interview question sections:

1. Basic theory of software testing, 2. web, app, interface function testing, 3. network, 4. database, 5. linux

6. Web, app, interface automation, 7. Performance testing, 8. Programming basics, 9. HR interview questions, 10. Open test questions, 11. Security testing, 12. Computer basics

 

How to obtain documents:

This document should be the most comprehensive and complete preparation warehouse for friends who want to engage in [software testing]. This warehouse has also accompanied me through the most difficult journey. I hope it can also help you!

Guess you like

Origin blog.csdn.net/2301_76643199/article/details/133207035