Springboot——junit测试

Springboot——junit测试

      • 参考博客
      • 测试过程
      • 测试controller
      • 问题日志

参考博客

Spring Boot 2.x使用Mockito进行测试
说一说在SpringBoot写单元测试遇到的坑

测试过程

  • RestfulApplicationTests.java
package com.antrain.restful;

import com.antrain.restful.controller.UserController;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;


@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@AutoConfigureMockMvc
class RestfulApplicationTests {
     

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserController userController;


    /**
     * 1、mockMvc.perform执行一个请求。
     * 2、MockMvcRequestBuilders.get("XXX")构造一个请求。
     * 3、ResultActions.param添加请求传值
     * 4、ResultActions.accept(MediaType.TEXT_HTML_VALUE))设置返回类型
     * 5、ResultActions.andExpect添加执行完成后的断言。
     * 6、ResultActions.andDo添加一个结果处理器,表示要对结果做点什么事情
     * 比如此处使用MockMvcResultHandlers.print()输出整个响应结果信息。
     * 5、ResultActions.andReturn表示执行完成后返回相应的结果。
     */


    @Test
    public void loginTest() throws Exception {
     
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("userName", "admin");
        params.add("password", "admin");
        if (mockMvc == null) {
     
            System.out.println("程序出错....");
            return;
        }
        String msg = mockMvc.perform(MockMvcRequestBuilders.post("/admin/login")
                .params(params)).andReturn().getResponse().getContentAsString();
        System.out.println(msg.length());//0
        System.out.println(msg);
    }
}

测试controller

  • 测试UserController
    其他Java类参考Springboot——restful实践后端
package com.antrain.restful.controller;

import com.antrain.restful.entity.User;
import com.antrain.restful.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Controller
@RequestMapping("/admin")
public class UserController {
     

    @Resource
    private UserService userService;

    @GetMapping("/users")
    public String list(Model model){
     
        model.addAttribute("users",userService.queryAll());
        return "admin/list";
    }

    @GetMapping("/user")
    public  String toAdd(Model model){
     
        return "admin/add";
    }

    @PostMapping("/user")
    public String add(User user){
     
        System.out.println("传入参数:==="+user);
        userService.insert(user);
        return "redirect:/admin/users";
    }

    @GetMapping("/user/{id}")
    public String toEdit(@PathVariable("id") Integer id, Model model){
     
        model.addAttribute("user",userService.queryById(id));
        return "admin/add";
    }

    @PutMapping("/user")
    public String update(User user){
     
        System.out.println("传入参数:==="+user);
        System.out.println("修改前数据库内容:===="+userService.queryById(user.getId()));
        userService.update(user);
        System.out.println("修改后数据库内容:===="+userService.queryById(user.getId()));
        return "redirect:/admin/users";
    }

    @DeleteMapping("/user/{id}")
    public String del(@PathVariable("id") Integer id){
     
        System.out.println("修改前数据库内容:===="+userService.queryById(id));
        userService.del(id);
        System.out.println("修改后数据库内容:===="+userService.queryById(id));
        return "redirect:/admin/users";
    }
}

  • 创建测试类
    Springboot——junit测试_第1张图片
    Springboot——junit测试_第2张图片
  • 测试类UserControllerTest.java
package com.antrain.restful.controller;

import org.junit.Assert;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;

//@Transactional 执行完后对数据库进行回滚

@RunWith(SpringRunner.class)
@Transactional
@SpringBootTest
class UserControllerTest {
     

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @BeforeEach
    void setUp() {
     
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @AfterEach
    void tearDown() {
     
    }

    @Test
    void list() throws Exception {
     
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/admin/users"))
                .andReturn();
        ModelAndView modelAndView=mvcResult.getModelAndView();//获取模型和试图
        System.out.println(modelAndView.getModel());
        //System.out.println(modelAndView.getView());
        MockHttpServletResponse response = mvcResult.getResponse();
        //拿到请求返回码
        int status = response.getStatus();
        //拿到结果
        String contentAsString = response.getContentAsString();
        System.out.println("status ===="+status);
        //System.out.println("result ====" + contentAsString); html内容
    }

    @Test
    void add() throws Exception {
     
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("username", "super");
        params.add("password", "123456");
        params.add("sex","M");
        params.add("birth","2020-02-02");
        MvcResult msg = mockMvc.perform(MockMvcRequestBuilders.post("/admin/user")
                .params(params)).andReturn();
        Assert.assertEquals(200,msg.getResponse().getStatus());

    }

    @Test
    void update() throws Exception {
     
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("id","1");
        params.add("username", "super");
        params.add("password", "123456");
        params.add("sex","M");
        params.add("birth","2020-02-02");
        MvcResult msg = mockMvc.perform(MockMvcRequestBuilders.put("/admin/user")
                .params(params)).andReturn();
        Assert.assertEquals(200,msg.getResponse().getStatus());
    }

    @Test
    void del() throws Exception {
     
        MvcResult msg = mockMvc.perform(MockMvcRequestBuilders.delete("/admin/user/1")).andReturn();
        Assert.assertEquals(200,msg.getResponse().getStatus());
    }
}
  • 测试结果
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

问题日志

  • Error running ‘RestfulApplicationTests.loginTest’: Failed to resolve org.junit.vintage:junit-vintage-engine:5.5.2
    移除依赖即可 注:可以在Diagrams移除较好
  • 先注释掉SiteWebMvcConfigurer配置类的addInterceptors()方法

你可能感兴趣的:(Spring+spring,boot,Springboot,测试)