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. 12_Java面向对象_第12天(构造方法、this、super)_讲义

    今日内容介绍 1.构造方法 2.this关键字 3.super关键字 4.综合案例 01构造方法引入 A:构造方法的引入 在开发中经常需要在创建对象的同时明确对象的属性值, 比如员工入职公司就要明确他 ...

  2. 转 理解vuex -- vue的状态管理模式

    转自:https://segmentfault.com/a/1190000012015742 vuex是什么? 先引用vuex官网的话: Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 ...

  3. Error: Unable to access jarfile D:\Apache\apache-jmeter-3.0\bin\ApacheJMete.jar

    双击jmeter.bat后,在cmd窗口显示Error: Unable to access jarfile D:\Apache\apache-jmeter-3.0\bin\ApacheJMete.ja ...

  4. Linux上两种网络连接方式

    模式一:NAT方式好处:路由器更换,或者交换机更换,网络仍然可以使用,所用使用最多 准备工作: 查看VMware服务器启动情况,五个全开模式 vmnet8开启模式 1 配置VMware交换机的ip地址 ...

  5. HHVM 3.0 发布,执行 PHP 的虚拟机

    HHVM 详细介绍 HipHop VM(HHVM)是Facebook推出的用来执行PHP代码的虚拟机,它是一个PHP的JIT(Just-In- Time)编译器,同时具有产生快速代码和即时编译的优点. ...

  6. Eslint 配置及规则说明(报错)

    https://blog.csdn.net/violetjack0808/article/details/72620859 https://blog.csdn.net/hsl0530hsl/artic ...

  7. JavaScript 稀奇的js语法

    function c(expression) { console.log(expression); } c(-0); // -0 c(-0 === +0); // true c((-0).toStri ...

  8. 重温SQL——行转列,列转行

    行转列,列转行是我们在开发过程中经常碰到的问题.行转列一般通过CASE WHEN 语句来实现,也可以通过 SQL SERVER 2005 新增的运算符PIVOT来实现.用传统的方法,比较好理解.层次清 ...

  9. FileZilla Server ftp 服务器下通过alias别名设置虚拟目录(多个分区)

    最近检查服务器的时候发现磁盘空间不够用了,正好有两个硬盘正好,一个硬盘还空着,正好通过ftp服务器的别名功能实现添加空间了,这样就不用重新弄机器了 说明:FileZilla Server 的虚拟目录设 ...

  10. python 求两个时间差

    def timeInterval(self): today = datetime.date.today() print today modifiedTime = os.stat(filename).s ...