spring-boot  controller 测试示例:

单元测试类

package com.zzhi;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.sun.org.apache.xerces.internal.xs.LSInputList;
import javafx.application.Application;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
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.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; /**
* Created by zhangzhii on 2017/7/13.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MaventestApplication.class)
@WebAppConfiguration
public class HomeControllerTest {
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); @Autowired
private WebApplicationContext wac; private MockMvc mockMvc; @Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
} @Test
public void test1() throws Exception {
String name="zzhi";
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/test1?name="+ name)).
andDo(print()).andReturn();
System.out.println(result.getResponse().getContentAsString());
} @Test
public void test02() throws Exception { User user = new User(, "zzhi");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
String requestBody = ow.writeValueAsString(user);
System.out.println(requestBody);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/test2?name=zzhi").
contentType(APPLICATION_JSON_UTF8).content(requestBody))
.andDo(print()).andReturn();
System.out.println(result);
} @Test
public void test03() throws Exception { List<User> list = new ArrayList<>();
list.add(new User(, "zzhi"));
list.add(new User(, "wang"));
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
String requestBody = ow.writeValueAsString(list);
System.out.println(requestBody);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/test3?name=zzhi").
contentType(APPLICATION_JSON_UTF8).content(requestBody))
.andDo(print()).andReturn();
System.out.println("结果:"+result.getResponse().getContentAsString());
} @Test
public void test04() throws Exception { Order order=new Order(); Address address=new Address();
address.setAdd1("陕西西安"); List<User> users = new ArrayList<>();
users.add(new User(, "zzhi"));
users.add(new User(, "wang")); order.setUsers(users);
order.setAddress(address);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
String requestBody = ow.writeValueAsString(order);
System.out.println(requestBody);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/test4?age=28").
param("name","张智").
contentType(APPLICATION_JSON_UTF8).content(requestBody))
.andDo(print()).andReturn();
System.out.println("结果:"+result.getResponse().getContentAsString());
}
}

Controller 类

package com.zzhi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest;
import java.util.List; /**
* Created by zhangzhii on 2017/7/12.
*/
@RestController()
public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @RequestMapping("/index")
@ResponseBody
public String Home() {
logger.info("home/index 开始");
return "hello world 111"; } @RequestMapping("/test1")
@ResponseBody
public String test1(String name) {
return name; }
@RequestMapping(
// consumes="application/json",
// produces="application/json",
method=RequestMethod.POST,
value="/test2")
@ResponseBody
public String test2(@RequestBody User user,String name) { return user.toString();
} @RequestMapping(
method=RequestMethod.POST,
value="/test3")
@ResponseBody
public String test3(@RequestBody List<User> users,String name) { return Integer.toString( users.size());
} @RequestMapping(
method=RequestMethod.POST,
value="/test4")
@ResponseBody
public String test4(HttpServletRequest request,@RequestBody Order order, String age) { String name= request.getParameter("name");
return age;
} }

PO:

package com.zzhi;

/**
* Created by zhangzhii on 2017/7/14.
*/
public class Address { public Address()
{ } @Override
public String toString() {
return "Address{" +
"add1='" + add1 + '\'' +
'}';
} public String getAdd1() {
return add1;
} public void setAdd1(String add1) {
this.add1 = add1;
} private String add1;
}
package com.zzhi;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;

/**
* Created by zhangzhii on 2017/7/14.
*/
public class Order { public Order(){ } public void setUsers(List<User> users) {
this.users = users;
}
@JsonProperty("users")
private List<User> users; public Address getAddress() {
return address;
} public void setAddress(Address address) {
this.address = address;
} private Address address; public List<User> getUsers() {
return users;
}
}
package com.zzhi;

import java.util.Date;

/**
* Created by zhangzhii on 2017/7/14.
*/
public class User { public User(){ }
public User(int age ,String name)
{
this.age=age;
this.name=name;
this.createTime= new Date();
} private int age;
private String name; @Override
public String toString() {
return "User{" +
"age=" + age +
", name='" + name + '\'' +
", createTime=" + createTime +
'}';
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} private Date createTime; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} }

pox:

    <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.</version>
</dependency>
</dependencies>

github

05-11 22:14