springboot03-unittest mockmvc单元测试

时间:2023-03-04 10:42:26

整个项目结构:

springboot03-unittest mockmvc单元测试

定义user实体类

package com.mlxs.springboot.dto;

import java.util.HashMap;
import java.util.Map; /**
* User类描述:
*
* @author yangzhenlong
* @since 2017/2/13
*/
public class User { private int id;
private String name; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public static Map<Integer, User> buildUserList(){
Map<Integer, User> userMap = new HashMap<>(); for(int i=1; i<=5; i++){
User user = new User();
user.setId(i);
user.setName("测试" + i);
userMap.put(i, user);
} return userMap;
}
}

MainApp启动类:

package com.mlxs.springboot.web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext; /**
* MainApp类描述:
*
* @author yangzhenlong
* @since 2017/2/13
*/
@SpringBootApplication
public class MainApp { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(MainApp.class, args);
/*String[] beanDefinitionNames = context.getBeanDefinitionNames();
System.out.println("-------- bean名称打印 --------");
for (String name : beanDefinitionNames) {
System.out.println(name);
}*/
}
}

UserService接口类:

public interface UserService {

    /**
* 查询所有用户
* @return
*/
Map<Integer, User> getAllUsers(); /**
* 根据Id查询
* @param id
* @return
*/
User getUserById(Integer id); /**
* 更新
* @param user
* @return
*/
User updateUserById(User user); /**
* 添加
* @param user
* @return
*/
User addUser(User user); /**
* 删除
* @param id
* @return
*/
boolean deleteUser(Integer id);
}

Service实现类:

@Service
public class UserServiceImpl implements UserService{ private static Map<Integer, User> userMap = User.buildUserList(); /**
* 查询所有用户
* @return
*/
public Map<Integer, User> getAllUsers(){
return userMap;
} /**
* 根据Id查询
* @param id
* @return
*/
public User getUserById(Integer id){
return userMap.get(id);
} /**
* 更新
* @param user
* @return
*/
public User updateUserById(User user){
if(null == userMap.get(user.getId())){
throw new RuntimeException("用户不存在");
}
userMap.put(user.getId(), user);
return user;
} /**
* 添加
* @param user
* @return
*/
public User addUser(User user){
if(null != userMap.get(user.getId())){
throw new RuntimeException("用户已存在");
}
userMap.put(user.getId(), user);
return user;
} /**
* 删除
* @param id
* @return
*/
public boolean deleteUser(Integer id){
if(null == userMap.get(id)){
throw new RuntimeException("用户不存在");
}
userMap.remove(id);
return true;
}
}

rest接口类UserController:

@RestController()
@RequestMapping("/")
public class UserController { private static Map<Integer, User> userMap = User.buildUserList(); /**
* 查询所有用户
* @return
*/
@RequestMapping(value = "/user", method = RequestMethod.GET)
public Map<Integer, User> getAllUsers(){
return userMap;
} /**
* 根据Id查询
* @param id
* @return
*/
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public User getUserById(Integer id){
return userMap.get(id);
} /**
* 更新
* @param user
* @return
*/
@RequestMapping(value = "/user", method = RequestMethod.PUT)
public User updateUserById(User user){
if(null == userMap.get(user.getId())){
throw new RuntimeException("用户不存在");
}
userMap.put(user.getId(), user);
return user;
} /**
* 添加
* @param user
* @return
*/
@RequestMapping(value = "/user", method = RequestMethod.POST)
public User addUser(User user){
if(null != userMap.get(user.getId())){
throw new RuntimeException("用户已存在");
}
userMap.put(user.getId(), user);
return user;
} /**
* 删除
* @param id
* @return
*/
@RequestMapping(value = "/user", method = RequestMethod.DELETE)
public String deleteUser(Integer id){
if(null == userMap.get(id)){
throw new RuntimeException("用户不存在");
}
userMap.remove(id);
return "delete success";
}
}

1.mockmvc针对service的单元测试:

UserServiceTest
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mlxs.springboot.dto.User;
import com.mlxs.springboot.web.MainApp;
import com.mlxs.springboot.web.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /**
* UserWebTest类描述:
*
* @author yangzhenlong
* @since 2017/2/13
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MainApp.class)
public class UserServiceTest { @Autowired
private UserService userService;
@Autowired
private ObjectMapper om; @Test
public void testAll() throws JsonProcessingException {
this.list();
this.add();
this.update();
this.delete();
} @Test
public void list() throws JsonProcessingException {
System.out.println("\n----------查询----------");
this.print(userService.getAllUsers());
} @Test
public void add(){
System.out.println("\n----------添加----------");
User add = new User();
add.setId(10);
add.setName("这是新添加");
userService.addUser(add);
this.print(userService.getAllUsers());
} @Test
public void update(){
System.out.println("\n----------更新----------");
User user = userService.getUserById(2);
user.setName("测试222");
userService.updateUserById(user);
this.print(userService.getAllUsers());
} @Test
public void delete(){
System.out.println("\n----------删除----------");
userService.deleteUser(3);
this.print(userService.getAllUsers());
} private void print(Object obj){
try {
System.out.println(om.writeValueAsString(obj));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}

执行testAll()方法结果:

springboot03-unittest mockmvc单元测试

2.mockmvc针对rest接口类的测试:

UserWebTest:
import com.mlxs.springboot.web.UserController;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; /**
* UserWebTest类描述:
*
* @author yangzhenlong
* @since 2017/2/13
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MockServletContext.class)
@WebAppConfiguration //启动一个真实web服务,然后调用Controller的Rest API,待单元测试完成之后再将web服务停掉
public class UserWebTest { private MockMvc mockMvc; @Before
public void setMockMvc(){
mockMvc = MockMvcBuilders.standaloneSetup(new UserController()).build();//设置要mock的Controller类,可以是多个
} @Test
public void testAll() throws Exception {
//1.查询
String queryResult = mockMvc.perform(MockMvcRequestBuilders.get("/user"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("id")))
.andReturn().getResponse().getContentAsString();
System.out.println("----------查询----------\n" + queryResult);
//2.添加
String addResult = mockMvc.perform(MockMvcRequestBuilders.post("/user").param("id", "10").param("name", "新添加"))
.andReturn()
.getResponse()
.getContentAsString();
System.out.println("----------添加----------\n" + addResult);
//3.更新
String updateResult = mockMvc.perform(MockMvcRequestBuilders.put("/user").param("id", "3").param("name", "更新333"))
.andReturn()
.getResponse()
.getContentAsString();
System.out.println("----------更新----------\n" + updateResult);
//4.删除
String deleteResult = mockMvc.perform(MockMvcRequestBuilders.delete("/user").param("id", "1"))
.andReturn()
.getResponse()
.getContentAsString();
System.out.println("----------删除----------\n" + deleteResult);
}
}

执行testAll()方法后结果:

springboot03-unittest mockmvc单元测试