spring boot RESTfuldemo测试类

RESTful 架构一个核心概念是“资源”(Resource)。从 RESTful 的角度看,网络里的任何东西都是资源,它可以是一段文本、一张图片、一首歌曲、一种服务等,每个资源都对应一个特定的 URI(统一资源定位符),并用它进行标示,访问这个 URI 就可以获得这个资源。

互联网中,客户端和服务端之间的互动传递的就只是资源的表述,我们上网的过程,就是调用资源的 URI,获取它不同表现形式的过程。这种互动只能使用无状态协议 HTTP,也就是说,服务端必须保存所有的状态,客户端可以使用 HTTP 的几个基本操作,包括 GET(获取)、POST(创建)、PUT(更新)与 DELETE(删除),使得服务端上的资源发生“状态转化”(State Transfer),也就是所谓的“表述性状态转移”。

Spring Boot 对 RESTful 的支持

Spring Boot 全面支持开发 RESTful 程序,通过不同的注解来支持前端的请求,除了经常使用的注解外,Spring Boot 还提了一些组合注解。这些注解来帮助简化常用的 HTTP 方法的映射,并更好地表达被注解方法的语义。

  • @GetMapping,处理 Get 请求
  • @PostMapping,处理 Post 请求
  • @PutMapping,用于更新资源
  • @DeleteMapping,处理删除请求
  • @PatchMapping,用于更新部分资源

测试类:

package com.example;

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.test.context.junit4.SpringRunner;
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.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MessageControllerTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
        saveMessages();//初始化数据
    }

    //获取所有初始化数据get请求
    @Test
    public void getAllMessages() throws Exception {
        String mvcResult= mockMvc.perform(MockMvcRequestBuilders.get("/messages")).andReturn().getResponse().getContentAsString();
        System.out.println("Result === "+mvcResult);
    }

    //获取单个消息get请求
    @Test
    public void getMessage() throws Exception {
        String mvcResult= mockMvc.perform(MockMvcRequestBuilders.get("/message/6")).andReturn().getResponse().getContentAsString();
        System.out.println("Result === "+mvcResult);
    }

    //更新 ID 为 6 的消息体。测试修改(put 请求)
    @Test
    public void modifyMessage() throws Exception {
        final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("id", "6");
        params.add("text", "text");
        params.add("summary", "summary");
        String mvcResult= mockMvc.perform(MockMvcRequestBuilders.put("/message").params(params))
                .andReturn().getResponse().getContentAsString();
        System.out.println("Result === "+mvcResult);
    }

    //测试局部修改(patch 请求)
    @Test
    public void patchMessage() throws Exception {
        final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("id", "6");
        params.add("text", "text");
        String mvcResult= mockMvc.perform(MockMvcRequestBuilders.patch("/message/text")
                .params(params)).andReturn().getResponse().getContentAsString();
        System.out.println("Result === "+mvcResult);
    }

    //删除 ID 为 6 的消息体,最后重新查询所有的消息
    @Test
    public void deleteMessage() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.delete("/message/6")).andReturn();
        String mvcResult= mockMvc.perform(MockMvcRequestBuilders.get("/messages"))
                .andReturn().getResponse().getContentAsString();
        System.out.println("Result === "+mvcResult);
    }

    @Test
    public void saveMessage() throws Exception {
        final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("text", "text");
        params.add("summary", "summary");
        String mvcResult=  mockMvc.perform(MockMvcRequestBuilders.post("/message").params(params)).andReturn().getResponse().getContentAsString();
        System.out.println("Result === "+mvcResult);
    }

    private void  saveMessages()  {
        for (int i=1;i<10;i++){
            final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("text", "text"+i);
            params.add("summary", "summary"+i);
            try {
                MvcResult mvcResult=  mockMvc.perform(MockMvcRequestBuilders.post("/message").params(params)).andReturn();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

控制层:

package com.example.controller;

import com.example.domain.Message;
import com.example.service.MessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/")
public class MessageController {

    @Autowired
    private MessageRepository messageRepository;

    // 获取所有消息体
    @GetMapping(value = "messages")
    public List<Message> list() {
        List<Message> messages = this.messageRepository.findAll();
        return messages;
    }

    // 创建一个消息体
    @PostMapping(value = "message")
    public Message create(Message message) {
        message = this.messageRepository.save(message);
        return message;
    }

    // 使用 put 请求进行修改
    @PutMapping(value = "message")
    public Message modify(Message message) {
        Message messageResult=this.messageRepository.update(message);
        return messageResult;
    }

    // 更新消息的 text 字段
    @PatchMapping(value="/message/text")
    public Message patch(Message message) {
        Message messageResult=this.messageRepository.updateText(message);
        return messageResult;
    }

    @GetMapping(value = "message/{id}")
    public Message get(@PathVariable Long id) {
        Message message = this.messageRepository.findMessage(id);
        return message;
    }

    @DeleteMapping(value = "message/{id}")
    public void delete(@PathVariable("id") Long id) {
        this.messageRepository.deleteMessage(id);
    }
}

接口层

package com.example.service;

import com.example.domain.Message;

import java.util.List;

public interface MessageRepository {
    public List<Message> findAll();

    public Message save(Message message);

    public Message update(Message message);

    public Message updateText(Message message);

    public Message findMessage(Long id);

    public void deleteMessage(Long id);
}

服务层

package com.example.service.impl;

import com.example.domain.Message;
import com.example.service.MessageRepository;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;

@Service("messageRepository")
public class InMemoryMessageRepository implements MessageRepository {

    private static AtomicLong counter = new AtomicLong();
    private final ConcurrentMap<Long, Message> messages = new ConcurrentHashMap<>();

    @Override
    public List<Message> findAll() {
        List<Message> messages = new ArrayList<Message>(this.messages.values());
        return messages;
    }

    @Override
    public Message save(Message message) {
        Long id = message.getId();
        if (id == null) {
            id = counter.incrementAndGet();
            message.setId(id);
        }
        this.messages.put(id, message);
        return message;
    }

    @Override
    public Message update(Message message) {
        this.messages.put(message.getId(), message);
        return message;
    }

    @Override
    public Message updateText(Message message) {
        Message msg=this.messages.get(message.getId());
        msg.setText(message.getText());
        this.messages.put(msg.getId(), msg);
        return msg;
    }

    @Override
    public Message findMessage(Long id) {
        return this.messages.get(id);
    }

    @Override
    public void deleteMessage(Long id) {
        this.messages.remove(id);
    }
}

原文地址:https://www.cnblogs.com/gjq1126-web/p/11781355.html

时间: 2024-08-29 16:44:08

spring boot RESTfuldemo测试类的相关文章

Spring Boot RestApi 测试教程 Mock 的使用

测试 Spring Boot Web 的时候,我们需要用到 MockMvc,即系统伪造一个 mvc 环境.本章主要编写一个基于 RESTful API 正删改查操作的测试用例.本章最终测试用例运行结果如下: 1 MockMvc 简介 Spring Boot Web 项目中我们采用 MockMvc 进行模拟测试 方法 说明 mockMvc.perform 执行一个请求 MockMvcRequestBuilders.get("XXX") 构造一个请求 ResultActions.param

Spring Boot(十二):Spring Boot 如何测试打包部署

有很多网友会时不时的问我, Spring Boot 项目如何测试,如何部署,在生产中有什么好的部署方案吗?这篇文章就来介绍一下 Spring Boot 如何开发.调试.打包到最后的投产上线. 开发阶段 单元测试 在开发阶段的时候最重要的是单元测试了, Spring Boot 对单元测试的支持已经很完善了. 1.在 pom 包中添加 spring-boot-starter-test 包引用 <dependency> <groupId>org.springframework.boot&

Spring Boot自动配置类

http://docs.spring.io/spring-boot/docs/current/api/overview-summary.html http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#auto-configuration-classes 前提 1.一般来说,xxxAware接口,都提供了一个setXxx的方法,以便于其实现类将Xxx注入自身的xxx字段中,从而进行操作. 例如 Applicatio

解决spring boot中普通类中使用service为null 的方法

我使用的是springboot+mybatisplus +mysql1.创建一个SpringUtil工具类 import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public final class SpringUtil im

spring seurity集成spring boot使用DelegatingSecurityContextAsyncTaskExecutor类异步授权authentication登录登出退出信息@async

方法1:将SecurityContextHolder的策略更改为MODE_INHERITABLETHREADLOCAL <beans:bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <beans:property name="targetClass" value="org.springframework.security.co

Spring Boot应用的测试——Mockito

Spring Boot应用的测试——Mockito Spring Boot可以和大部分流行的测试框架协同工作:通过Spring JUnit创建单元测试:生成测试数据初始化数据库用于测试:Spring Boot可以跟BDD(Behavier Driven Development)工具.Cucumber和Spock协同工作,对应用程序进行测试. 进行软件开发的时候,我们会写很多代码,不过,再过六个月(甚至一年以上)你知道自己的代码怎么运作么?通过测试(单元测试.集成测试.接口测试)可以保证系统的可维

使用Ratpack和Spring Boot打造高性能的JVM微服务应用

使用Ratpack和Spring Boot打造高性能的JVM微服务应用 这是我为InfoQ翻译的文章,原文地址:Build High Performance JVM Microservices with Ratpack & Spring Boot,InfoQ上的中文地址:使用Ratpack与Spring Boot构建高性能JVM微服务. 在微服务天堂中Ratpack和Spring Boot是天造地设的一对.它们都是以开发者为中心的运行于JVM之上的web框架,侧重于生产率.效率以及轻量级部署.他

Spring boot(4)-应用打包部署

摘自: http://blog.csdn.net/hguisu/article/details/51072683 1.Spring Boot内置web spring Boot 其默认是集成web容器的,启动方式由像普通Java程序一样,main函数入口启动.其内置Tomcat容器或Jetty容器,具体由配置来决定(默认Tomcat).当然你也可以将项目打包成war包,放到独立的web容器中(Tomcat.weblogic等等),当然在此之前你要对程序入口做简单调整. 对server的几个常用的配

maven+spring boot搭建简单微服务

项目需要使用spring boot,所以自学了几天,仅提供给新手,请根据文档查看-该项目仅是测试项目,并不完善和严谨,只实现了需要使用的基本功能.写该博客一是希望能够帮助刚学习的新人,二是加深自己的印象,如果忘了也可以再看看,有些片段是从其他博客学习来的,如有问题希望能提出来,由衷的表示感谢. 主要开发环境:jdk:1.8: maven:3.3:tomcat:8等. 涉及技术:spring boot.springMVC.maven.JdbcTemplate.json.HttpClient等. 推