项目结构
Maven - pom.xml
pom.xml中添加如下依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
<scope>provided</scope>
</dependency>
junit单元测试 ,lombok提供实体类的getter,setter
com.inverseli.learning - HelloApplication.java
package com.inverseli.learning;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @date:2018年9月19日 上午11:38:55
* @author liyuhao
* @version 1.0
* @since JDK 1.8
* @description:
*/
@SpringBootApplication
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class,args);
}
}
com.inverseli.learning/entity - User.java
package com.inverseli.learning.entity;
import lombok.Data;
/**
* @date:2018年9月21日 上午10:49:21
* @author liyuhao
* @version 1.0
* @since JDK 1.8
* @description:
*/
@Data
public class User {
private Long id;
private String name;
private Integer age;
}
com.inverseli.learning/controller
HelloController.java
package com.inverseli.learning.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @date:2018年9月21日 上午10:51:40
* @author liyuhao
* @version 1.0
* @since JDK 1.8
* @description:
*/
@RestController
public class HelloController {
@RequestMapping("/hello")
public String index() {
return "Hello World";
}
}
UserController.java
package com.inverseli.learning.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.inverseli.learning.entity.User;
/**
* @date:2018年9月21日 上午10:53:20
* @author liyuhao
* @version 1.0
* @since JDK 1.8
* @description:
*/
@RestController
@RequestMapping("/users") // /user请求映射到此controller
public class UserController {
// 类似与ConcurrentHashMap,Map同步
static Map<Long,User> users = Collections.synchronizedMap(new HashMap<Long,User>());
// @GetMapping = @RequestMapping(value="/",method=RequestMethod.GET)
@RequestMapping(value="/",method=RequestMethod.GET)
public List<User> getUserList() {
List<User> userList = new ArrayList<User>(users.values());
return userList;
}
@PostMapping("/")
public String postUser(@ModelAttribute User user) {
// @ModelAttribute绑定参数,或者 @RequestParam从页面传递参数
users.put(user.getId(), user);
return "success";
}
@GetMapping(value="/{id}")
public User getUser(@PathVariable Long id) {
// url的id可通过@PathVariable绑定到参数中
return users.get(id);
}
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public String putUser(@PathVariable Long id, @ModelAttribute User user) {
// 处理"/users/{id}"的PUT请求,用来更新User信息
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
return "success";
}
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
// 处理"/users/{id}"的DELETE请求,用来删除User
users.remove(id);
return "success";
}
}
ApplicationTest
package com.inverseli.learning;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.http.MediaType;
import com.inverseli.learning.controller.HelloController;
import com.inverseli.learning.controller.UserController;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* @date:2018年9月21日 上午11:10:47
* @author liyuhao
* @version 1.0
* @since JDK 1.8
* @description:
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
//@SpringApplicationConfiguration(classes = HelloApplication.class)
//@SpringBootTest(classes = HelloApplication.class)
public class ApplicationTest {
private MockMvc mvc;
// @Autowired
// private WebApplicationContext wac;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(
new HelloController(),
new UserController()).build();
// mvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello World")));
}
@Test
public void testUserController() throws Exception {
// testUserController
RequestBuilder request = null;
// 1.get查user列表
request = get("/users/");
mvc.perform(request)
.andExpect(status().isOk())
.andExpect(content().string(equalTo("[]")));
// 2.post提交一个user
request = post("/users/")
.param("id", "1")
.param("name", "测试大师")
.param("age", "20");
mvc.perform(request)
// .andDo(MockMvcResultHandlers.print())
.andExpect(content().string(equalTo("success")));
// 3、get获取user列表,应该有刚才插入的数据
request = get("/users/");
mvc.perform(request)
.andExpect(status().isOk())
.andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"测试大师\",\"age\":20}]")));
// 4、put修改id为1的user
request = put("/users/1")
.param("name", "测试终极大师")
.param("age", "30");
mvc.perform(request)
.andExpect(content().string(equalTo("success")));
// 5、get一个id为1的user
request = get("/users/1");
mvc.perform(request)
.andExpect(content().string(equalTo("{\"id\":1,\"name\":\"测试终极大师\",\"age\":30}")));
// 6、del删除id为1的user
request = delete("/users/1");
mvc.perform(request)
.andExpect(content().string(equalTo("success")));
// 7、get查一下user列表,应该为空
request = get("/users/");
mvc.perform(request)
.andExpect(status().isOk())
.andExpect(content().string(equalTo("[]")));
}
}
初始化MockMvc的两种方式
- 第一种
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class ApplicationTest {
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(
new HelloController(),
new UserController()).build();
}
}
- 第二种
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = HelloApplication.class)
public class ApplicationTest {
private MockMvc mvc;
// 多数人推荐这种,不知道原因
@Autowired
private WebApplicationContext wac;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
}
其中@SpringApplicationConfiguration(classes = HelloApplication.class)已经过时,改为@SpringBootTest(classes = HelloApplication.class)