spring boot RESTfuldemo test class

RESTful architecture is a core concept of "resource" (Resource). RESTful from the perspective of the network resource is anything, it can be a piece of text, a picture, a song, a service etc., each resource corresponds to a specific URI (uniform resource locator), and use it to mark a visit to this URI can get the resources.

 

Internet, just representation of resource interaction between the client and server delivered our online process, is to call the resource URI, gets its different manifestations of the process. This interaction can only use the stateless HTTP protocol, that is, the server must save all of the state, the client can use a few basic HTTP operations, including GET (acquisition), POST (create), PUT (update) and dELETE (delete), so that the resources on the server happen "state transformation" (state transfer), also known as "Representational state transfer."

 

Spring Boot support for a RESTful

 

Spring Boot full support for RESTful development programs, to front-end support requests through different notes, in addition to the regular use of annotations, Spring Boot also mention some combination of notes. These annotations to help simplify the mapping method commonly HTTP, and better methods annotated semantic expression.

 

  • @GetMapping, Get Request Processing
  • @PostMapping, Post Processing Request
  • @PutMapping, used to update the resource
  • @DeleteMapping, handle delete request
  • @PatchMapping, used to update some of the resources

Test categories:

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 (); // initialize the data 
    }

    // Get all initialization data get request 
    @Test
     public  void GetAllMessages () throws Exception {
        String mvcResult= mockMvc.perform(MockMvcRequestBuilders.get("/messages")).andReturn().getResponse().getContentAsString();
        System.out.println("Result === "+mvcResult);
    }

    // Get a single get request message 
    @Test
     public  void the getMessage () throws Exception {
        String mvcResult= mockMvc.perform(MockMvcRequestBuilders.get("/message/6")).andReturn().getResponse().getContentAsString();
        System.out.println("Result === "+mvcResult);
    }

    // Update message ID to body 6. Modifying test (put request) 
    @Test
     public  void modifyMessage () throws Exception {
         Final MultiValueMap <String, String> the params = new 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);
    }

    // Test partial modification (Patch request) 
    @Test
     public  void patchMessage () throws Exception {
         Final MultiValueMap <String, String> the params = new 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);
    }

    // delete the message ID 6, and finally re-query all messages 
    @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 ();
            }
        }
    }
}

Control layer:

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;

    // Get all the message body 
    @GetMapping (value = "messages" )
     public List <the Message> List () {
        List<Message> messages = this.messageRepository.findAll();
        return messages;
    }

    // Create a message body 
    @PostMapping (value = "Message" )
     public the Message Create (the Message Message) {
        message = this.messageRepository.save(message);
        return message;
    }

    // Use the put request to modify 
    @PutMapping (value = "Message" )
     public the Message Modify (the Message Message) {
        Message messageResult=this.messageRepository.update(message);
        return messageResult;
    }

    // update message text field 
    @PatchMapping (value = "/ Message / text" )
     public the Message Patch (the 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);
    }
}

Interface Layer

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);
}

Service Layer

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);
    }
}

 

Guess you like

Origin www.cnblogs.com/gjq1126-web/p/11781355.html