What are the methods of springboot 2 game integration test components?


1、 Background description
In version development, the time period is roughly divided into: requirements, development and testing;

Requirements stage: understand the requirements and do a good job in interface design;
Development stage: complete function development and docking;
Test online: self test, test, repair and online;
In fact, there are two core tasks in the development stage, development and process self-test. The fundamental purpose of self-test is to solve possible problems in advance; If there are no two key steps of self-test and testing, the problem will be passed on to more users, resulting in more resource consumption;

Self test is for development, and test raising is for professional testers. If problems are found and solved in the self-test stage as far as possible, a problem will not affect more people in team cooperation. If a simple problem rises to the team cooperation level, it is likely to enlarge the problem itself.

If you want to do a good job, you must first sharpen your tools. If you want to do a good job in the self-test process, it is very important to learn to use tools to improve efficiency. The key of self-test is to find and solve problems. Therefore, choosing good and efficient tools can greatly reduce the time consumption of self-test.

The following is a brief summary of several commonly used test tools and means in their own development process. It is not the quality of the comparison method, but the existence is reasonable. The fundamental purpose is to select reasonable means in different scenarios and quickly solve problems.

2、 Postman tool
Postman is a common interface testing tool. It can test interfaces quickly in the development process. It is powerful, simple and convenient. It can not only test single interfaces, but also manage interfaces in blocks and run them in batches:

On the whole, the tool is easy to use. It is suitable for the rapid test of interfaces in the development stage, or the test of a single interface in the process of solving problemsgameParameters have the ability of storage and memory, which is also a major reason for their popularity.

However, the tool is not suitable for complex process testing. For example, it needs to be processed separately according to the response message of the last interface, or the data of an interface response needs to be filled in the next request.

3、 Swagger documentation
Swagger management interface document is a very common component in current services. It can quickly generate interface description information through simple annotation of interfaces and objects, and can send requests to the interface to assist in debugging. This document greatly improves the efficiency in front and back-end joint debugging.

The management of interface document itself is a troublesome thing. The interface is usually adjusted continuously according to the business. If you maintain an interface document alone, you need to pay a lot of time and cost, and it is easy to have problems. This problem can be avoided by using swagger.

Marking objects with swagger annotations

@Tablename (“jt_activity”) @ apimodel (value = “activity Po object”, description = “activity information table [jt_activity]”) public class activity {@ apimodelproperty (value = “primary key ID”) @ tableid (type = idtype. Auto) private integer ID; @ apimodelproperty (value = “activity subject”) private string activitytitle; @ apimodelproperty (value = “contact number”) private String contactPhone; @ Apimodelproperty (value = “1 online, 2 offline”) private integer [email protected] Apimodelproperty (value = “hosting address”) private string [email protected] Apimodelproperty (value = “organizer”) private string [email protected] Apimodelproperty (value = “creation time”) private date createtime;}
Marking interfaces with swagger annotations

@Activity (@ aptactivityservice. Aptactivityid) (“public activity”); activity (@ aptactivityservice. Aptactivityactivity “); activity (@ activity)@ Apioperation (“primary key query”) @ getmapping (“/ activity / {ID}”) public activity getbyid (@ pathvariable (“Id”) integer ID) {return activityservice.getbyid (ID);}@ Apioperation (“modify activity”) @ putmapping (“/ activity”) public Boolean updatebyid (@ requestbody activity) {return activityservice. Updatebyid (activity);}}

Generally speaking, the input and key return parameter objects on interface classes and methods are marked based on swagger annotations COM, which can avoid maintaining the interface document separately.

Swagger interface documents play the role of documents in the development process. The interfaces that really use swagger to debug are often simple interfaces that add, delete, modify and check. This tool is also not suitable for the testing of complex processes.

4、 Testresttemplate class
The test API integrated in the springboot test package depends on the test package and can access the control layer interface, which is very convenient to complete the interaction process:

Jar package dependency

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope></dependency>
Use case

@RunWith(SpringRunner.class)@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)public class ActivityTest01 { protected static Logger logger = LoggerFactory.getLogger(ActivityTest01.class) ; @Resource private TestRestTemplate restTemplate; private Activity activity = null ; @Before public void before (){ activity = restTemplate.getForObject( “/activity/{id}”, Activity. class,1); logger. info(“\n”+JSONUtil.toJsonPrettyStr(activity)); } @ Test public void updatebyid() {if (activity! = null) {activity.setcreatetime (New date()); activity.setorganizer (“one merchant”); resttemplate.put (“/ activity”, activity);}}@ After public void after (){ activity = restTemplate.getForObject(“/activity/{id}”, Activity.class,1); logger. info(“\n”+JSONUtil.toJsonPrettyStr(activity)); activity = null ; }}
It can be found in the testresttemplate source code that many functions are implemented by calling the resttemplate method based on the resttemplate encapsulation.

It is very flexible to write code to realize interface testing. It can be customized and developed according to the process. It is very suitable for moderately complex scenario testing. Why is this described here? Let’s talk about it in detail compared with HTTP requests.

5、 HTTP request mode
At present, the most flexible way to realize the HTTP request through the analog interface is to look at a simple case:

@Runwith (springrunner. Class) @ springboottest (webenvironment = springboottest. Webenvironment. Defined_port) public class activitytest03 {protected static logger logger = loggerfactory.getlogger (activitytest03. Class); protected static string req_url = “service address + port”; @ test public void testhttp() {/ / query string getres = httputil.get (req_url + “activity / 1”) ; logger. info(“\n {} “,JSONUtil.toJsonPrettyStr(getRes)); Activity activity = JSONUtil. toBean(getRes, Activity.class) ; // Add activity setId(null); activity. Setorganizer (“HTTP merchant”); String saveRes = HttpUtil. post(REQ_URL+”/activity”,JSONUtil.toJsonStr(activity)); logger. info(“\n {} “,saveRes); // Update activity setId(Integer.parseInt(saveRes)); activity. Setorganizer (“put merchant”); String putRes = HttpRequest. put(REQ_URL+”/activity”) . body(JSONUtil.toJsonStr(activity)). execute(). body(); logger. info(“\n {} “,putRes); }}
This method is very useful for complex business processes. Of course, personal habits are not excluded here. When testing complex processes, a simple scheme:

User information: simulate the token data in HTTP;
Business process: obtain the packaging parameter model through data;
Independent service management to simulate concurrent scenarios;
Generate analysis data results according to the execution process;
For the testing of complex business processes, the simulation of each node has certain difficulty. Usually, there are multiple services and library tables involved in the complete process, and the request links are complex. Testing the complete links based on a flexible automatic process can greatly improve the efficiency.

6、 Service layer test
The test method for the service layer is intended to test the logic of business implementation:

@Runwith (springrunner. Class) @ springboottest (classes = application. Class) public class activitytest04 {protected static logger logger logger = loggerfactory.getlogger (activitytest04. Class); @ Autowired private activityservice activityservice; @ test public void testservice() {/ / query activity = activityservice.getbyid (1); / / add activity.setid (null); activityService. save(activity) ; // Modify activity Setorganizer (“ser merchant”); activityService. updateById(activity) ; // Delete activityservice removeById(activity.getId()) ; }}
This test is not commonly used in the actual development process. Occasionally, it is difficult to implement a business method for targeted testing.

7、 Mockmvc mode
Mockmvc is also a test method provided by the springboot integration test package. Through object simulation, verify whether the interface meets the expectations:

@ [email protected] (SpringRunner.class)@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)public class ActivityTest02 { protected static Logger logger = LoggerFactory.getLogger(ActivityTest02.class) ; @Resource private MockMvc mockMvc ; private Activity activity = null ; @Before public void before () throws Exception { ResultActions resultAction = mockMvc.perform (MockMvcRequestBuilders.get(“/activity/{id}”,1)) ; MvcResult mvcResult = resultAction. andReturn() ; String result = mvcResult. getResponse(). getContentAsString(); activity = JSONUtil. toBean(result,Activity.class) ; } @ Test public void updatebyid() throws exception {activity.setid (null); activity.setcreatetime (New date()); activity.setorganizer (“one merchant”); resultactions resultaction = mockmvc.perform (mockmvcrequebuilders. Post (“/ activity”). Contenttype (mediatype. Application_json). Content (JSONUtil.toJsonStr(activity))) ; MvcResult mvcResult = resultAction. andReturn() ; String result = mvcResult. getResponse(). getContentAsString(); activity. setId(Integer.parseInt(result)); logger. info(“result : {} “,result); } @ After public void after() throws exception {activity. Setcreatetime (New date()); activity. Setorganizer (“update merchant”); resultactions resultaction = mockmvc. Perform (mockmvcrequebuilders. Put (“/ activity”). Contenttype (mediatype. Application_json). Content (jsonutil. Tojsonstr (activity)); mvcresult mvcresult = resultaction. Andreturn () ; String result = mvcResult. getResponse(). getContentAsString(); logger. info(“result : {} “,result); }}
For this mock type of test, it is very professional. It is usually rarely used by individuals. For the time being, there is no get to its essence.

8、 Mockito test
Mock is a very professional and standard test method, which needs to rely on powermock package:

<dependency> <groupId>org.powermock</groupId> <artifactId>powermock-core</artifactId> <scope>test</scope></dependency><dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito2</artifactId> <scope>test</scope></dependency><dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <scope>test</scope></dependency>
Simple use cases:

@Runwith (powermockrunner. Class) @ springboottestpublic class activitytest05 {@ test public void testmock() {set mockset = powermockito.mock (set. Class); powermockito. When (mockset. Size()). Thenreturn (10); int actual = mockset. Size(); int expected = 15; assert.assertequals (“return value does not meet expectations”, expected, actual);}@ Test public void testtitle() {string expecttitle = “mock subject”; activity activity = powermockito.mock (activity. Class); powermockito.when (activity. Getmocktitle()). Thenreturn (expecttitle); string activitittle = activity. Getmocktitle(); assert.assertnotequals (“subject matches”, expecttitle, actualttitle);}}
You can quickly simulate the complex object structure through mock to build the test method. Because it is rarely used, the same individual has not got to the point for the time being.