java-Springboot+Junit-Solve the problem of how to build request, response, session, cookie simulation encapsulation http request

java-Springboot+Junit-Solve the problem of how to build request, response, session, cookie simulation encapsulation http request

environment

  • springboot 1.5.6
  • jdk 1.8

introduction

It is very convenient to use Springboot to develop an interface based on Http that satisfies the RESTful style, and perfectly supports scenarios such as front-end and back-end separation, MVC, and microservices.
Most of the time in service development is spent debugging and testing. Small changes in the underlying logic as requirements change may produce a butterfly effect, which has a certain impact on the logic of partially dependent service functions.
During development, mock tests are generally done through Postman, but even for some services written by myself, after two months, it is estimated that even the basic parameters do not know what to pass.
The best way to solve this kind of problem is to use junit to do unit tests. After the test is passed, record the parameters and calls used at that time in the form of unit tests, that is, the test parameters are retained and can be quickly modified after subsequent logic modifications. Do regression testing.
When some services require authentication or parameters such as headers and cookies, how do we write unit tests.
The following introduces a method of constructing a request object to pass header parameters. Other types of parameters are similar, and everything can be mocked with a request object.

Build the Request object

We know that based on the Http mode, almost all parameters are contained in the Request object, and a request object must be constructed in order to use unit testing.
There are generally two ways to obtain the Request object during development.

  • Automatic injection based on spring
@PostMapping(value = "/data/buildCeateTableDDL")
@ApiOperation(value = "产品库数据库表创建服务", notes = "")
public void buildCeateTableDDL(@RequestBody String sqlTemplate,HttpServletResponse rsp,HttpServletRequest req) throws Exception {
    String html = dataSyncService.ceateTableDDL(sqlTemplate);
    rspWrite(rsp, html);
//        return ApiResult.ofSuccessResult(msg);
}
  • Use the RequestContextHolder object to obtain
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

After analyzing the logic of the two codes, it is found that both rely on the HttpServletRequest interface. When viewing the implementation class, it is found that the implementation class of MockHttpServletRequest is provided by springframework.
Look into this class, and find that there is no miserable constructor _ , and it will be ok if you just new it.

Maven dependencies

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

Build a junit-based springboot environment

First of all, you need to let junit run in the springboot environment. The main thing is to make all the injected objects take effect, otherwise you will inevitably report an error by directly using @Test to call the annotation-based method.
To build a test base class, when you need to use the springboot environment, just inherit it.

@RunWith(SpringRunner.class)
//@Transactional
@SpringBootTest(classes = StartApplication.class, webEnvironment = SpringBootTest.WebEnvironment.NONE)
@ActiveProfiles("") //指定环境参数 空=application.yml; local=application-local.yml,
public class TestBase {
    /**
     * 可以传递header参数
     * @param platform
     * @param region
     */
    public void setRequestHeader(String username,String pwd){
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.addHeader("username",username);
        request.addHeader("pwd",pwd);
        RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
    }
}

Call methods that depend on header parameters

public class xxxxxTest extends TestBase {
  
    @Before
    public void init(){
        setRequestHeader("admin","123456");
    }

    @Test
    public void testXXXX() throws Exception {
        ...
        Assert.assertTrue(...);
    }
}

Summarize

When I saw that the HttpServletRequest interface has 36 implementation classes, I wanted to implement this interface myself to build a wheel. But when I saw that the interface had as many as 50 methods that needed to be implemented, I dispelled this idea.
It's better to find out if there are any classes that can be used directly that have already been practiced.
To implement the HttpServletRequest interface is definitely helpful to us, but it is a bit "wrong" to complete business functions, which affects work efficiency.
The realization of a Request object may require you to understand a lot of knowledge points, unknown concepts and pitfalls waiting for you to step on, and improving work efficiency is the first priority! ! !
For the implementation of the HttpServletRequest interface, it seems to be a kind of diligence, but it is actually a manifestation of your lack of brains and thinking.

Don't use the hard work of the body to cover up the laziness of the mind! ! ! !

Guess you like

Origin blog.csdn.net/xxj_jing/article/details/130132761