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

spring-boot Test for Controller的更多相关文章

  1. Spring Boot Web 开发@Controller @RestController 使用教程

    在 Spring Boot 中,@Controller 注解是专门用于处理 Http 请求处理的,是以 MVC 为核心的设计思想的控制层.@RestController 则是 @Controller ...

  2. Spring boot进阶-配置Controller、interceptor...

    1.配置SpringBootApplication(对spring boot来说这是最基本) package io.github.syske.springboot31; import org.spri ...

  3. 为spring boot 写的Controller中的rest接口配置swagger

    1.pom.xml文件中加入下列依赖: <dependency> <groupId>io.springfox</groupId> <artifactId> ...

  4. spring boot之入门Controller常用注解

    Controller常用注解 @Controller  处理http请求 @RestController Spring4之后新加的注解,原来返回json数据需要@ResponseBody配合@Cont ...

  5. Spring Boot—11控制器Controller

    package com.sample.smartmap.controller; import org.springframework.beans.factory.annotation.Autowire ...

  6. spring boot controller路由 url 扫描不到问题

    spring boot项目出现controller的路由没被注册,原因:启动类application跟controller不在一个包中,扫描不到controller, 如启动类在com.oyx.a,c ...

  7. Springboot 系列(一)Spring Boot 入门篇

    注意:本 Spring Boot 系列文章基于 Spring Boot 版本 v2.1.1.RELEASE 进行学习分析,版本不同可能会有细微差别. 前言 由于 J2EE 的开发变得笨重,繁多的配置, ...

  8. Spring Boot 16 条最佳实践

    Spring Boot是最流行的用于开发微服务的Java框架.在本文中,我将与你分享自2016年以来我在专业开发中使用Spring Boot所采用的最佳实践.这些内容是基于我的个人经验和一些熟知的Sp ...

  9. Spring Boot 最流行的 16 条实践解读,你值得收藏!

    Spring Boot是最流行的用于开发微服务的Java框架.在本文中,我将与你分享自2016年以来我在专业开发中使用Spring Boot所采用的最佳实践.这些内容是基于我的个人经验和一些熟知的Sp ...

  10. Spring Boot 2.0 学习笔记(一)——JAVA EE简介

    本章内容:JAVA EE>Spring>Spring Boot 一.JAVA EE简介 1.1 Java ee优点:结束了Web开发的技术无序状态,让程序员.架构师用同一种思维去思考如何架 ...

随机推荐

  1. 3、第一个Python程序

    现在,了解了如何启动和退出Python的交互式环境,我们就可以正式开始编写Python代码了. 在写代码之前,请千万不要用“复制”-“粘贴”把代码从页面粘贴到你自己的电脑上.写程序也讲究一个感觉,你需 ...

  2. Beta阶段团队项目开发篇章2

    例会时间: 2016.12.4 例会照片 个人工作 上阶段任务验收: 组员任务都已完成. 任务分配 组员 任务内容 韩慧敏 对调查问卷的结果进行分析和总结,确定Beta阶段各任务的优先级,撰写相关博客 ...

  3. 结队第二次作业——WordCount进阶需求

    结队第二次作业--WordCount进阶需求 博客地址 051601135 岳冠宇 博客地址 051604103 陈思孝 博客地址 Github地址 具体分工 队友实现了爬虫功能,我实现了wordco ...

  4. git常用命令复习及其基本使用示例

    年后回来新上到项目,对于git的一些操作命令记得有点混乱了,所以特整理笔记如下: 一.git常用命令复习 查看当前分支:git branch (显示结果中带有*号的是当前分支)查看所有分支: git ...

  5. jmeter body 中文显示为乱码解决

    这种情况在jmeter3.0的版本中才会产生,注意:这不是乱码,而是由于3.0中优化body data后,使用默认的字体(Consolas)不支持汉字的显示.这样的情况可以这样调整:进入jmeter. ...

  6. js学习1

    js基础1: js组成: ECMAScript :解释器 .翻译 提供语言的基本功能 几乎没有兼容型问题 dom :document object model 有一些兼容型问题 bom :brower ...

  7. filebeat向kafka中传输数据报WARN Failed to connect to broker DOMSDev07:9092: dial tcp: lookup DOMSDev07: getaddrinfow: No such host is known.解决方法

    打开filebeat客户端所在机器C:\Windows\System32\drivers\etc目录,找到hosts文件 以记事本形式打开,在底部追加 “IP 主机名” 即可

  8. Eclipse HTML Editor

    需插件: 1.GEF 3.1 安装程序下载 下载地址: http://download.eclipse.org/tools/gef/downloads/drops/R-3.1-200507071758 ...

  9. php的数组转为对象

    有时候数组要转为对象操作,用对象的指向操作符,有两种方法 方法一: $arr=['a'=>10,'b'=>100,'c'=>'Hello']; $obj=(Object)$arr; ...

  10. PHP 字符串数组按照拼音排序的问题

    拼音排序的规则: 字符串包括特殊字符.数字.英文字符.中文字符等等,排序结果要求,特殊字符排在第一梯队,将其按照首个字符ascii码表进行排序,数字字符排在第二梯队,将首个字符数字按照数字大小排序,英 ...