spring-boot Test for Controller

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(28, "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(28, "zzhi"));
        list.add(new User(32, "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(28, "zzhi"));
        users.add(new User(32, "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.7</version>
        </dependency>
    </dependencies>
时间: 2024-12-08 19:15:54

spring-boot Test for Controller的相关文章

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

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

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

1.pom.xml文件中加入下列依赖: <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version></dependency> <dependency> <groupId>io.springfox</groupId&g

Spring Boot&mdash;11控制器Controller

package com.sample.smartmap.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.spring

spring boot之入门Controller常用注解

Controller常用注解 @Controller  处理http请求 @RestController Spring4之后新加的注解,原来返回json数据需要@ResponseBody配合@Controller,现在合并成@RestController @RequestMapping  配置url映射,value配置url方法路径,method配置请求方式, 例:@RequestMapping(value="hello",method = RequestMethod.GET) @Pa

spring boot学习随笔

Spring Boot 概述 ---------------------------------------------------------------------------------********************************-------------------------------------------------------------------- Spring Boot介绍: Spring Boot的目的在于创建和启动新的基于Spring框架的项目,S

两年摸爬滚打 Spring Boot,总结了这 16 条最佳实践

前言Spring Boot是最流行的用于开发微服务的Java框架.在本文中,我将与你分享自2016年以来我在专业开发中使用Spring Boot所采用的最佳实践.这些内容是基于我的个人经验和一些熟知的Spring Boot专家的文章. 在本文中,我将重点介绍Spring Boot特有的实践(大多数时候,也适用于Spring项目).以下依次列出了最佳实践,排名不分先后. 1.使用自定义BOM来维护第三方依赖 这条实践是我根据实际项目中的经历总结出的. Spring Boot项目本身使用和集成了大量

记一次Spring boot搭建过程

遇到的问题如下: 1.Spring Boot正常启动后,访问Controller报404问题描述: spring boot正常启动,通过 http://localhost:8000/hello/first 访问,一直报404 原因: 在搭建完项目之后,Application类是放在com.example.hello的包下面,而Controller类是放置在com.example.controller的包下面,导致spring boot无法扫描controller包下的内容(默认扫Applicat

Spring Boot集成smart-doc生成api文档

smart-doc是一个java restful api文档生成工具,smart-doc颠覆了传统类似swagger这种大量采用注解侵入来生成文档的实现方法.smart-doc完全基于接口源码分析来生成接口文档,完全做到零注解侵入,你只需要按照java标准注释的写,smart-doc就能帮你生成一个简易明了的markdown或是一个像GitBook样式的静态html文档.下面将介绍如何在Spring Boot项目中集成smart-doc生成一个简明的api文档. 注意: smart-doc已经被

【华为云技术分享】Spring Boot 最流行的 16 条实践解读!

Spring Boot是最流行的用于开发微服务的Java框架.在本文中,将与大家分享自2016年以来笔者在专业开发中使用Spring Boot所采用的最佳实践.这些内容是基于笔者个人经验和一些熟知的Spring Boot专家的文章. 在本文中,将重点介绍Spring Boot特有的实践(大多数时候,也适用于Spring项目).以下依次列出了最佳实践,排名不分先后. 1.使用自定义BOM来维护第三方依赖 这条实践是我根据实际项目中的经历总结出的. Spring Boot项目本身使用和集成了大量的开

Spring Boot如何让某个Controller支持跨源请求,以及如何让Controller类某个成员方法支持跨源请求

在前面我们已经讨论了Spring Boot 如何全局支持跨源请求.如果你想了解可以查看这篇文章 下面我们讨论另一种场景.有些时候,你需要让你的应用在大部分的时候,仅仅支持当前域名下的请求.而仅仅在极其特殊的几个场合下,才支持跨源请求.这个时候,你需要把跨源请求仅仅缩小在几个Controller上,或者Controller类的几个成员方法上.这个时候你需要用到如下的注解:@CrossOrigin(origins = "*", maxAge = 3600) .把这个注解放到 Control