Skip to content

Commit

Permalink
调整代码,处理报错,添加测试
Browse files Browse the repository at this point in the history
  • Loading branch information
mongoding committed May 8, 2018
1 parent af71fd9 commit 555b6cf
Show file tree
Hide file tree
Showing 11 changed files with 370 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class UserController {
@RequestMapping("/name")
public Object getUser() {

return "dingzhenhao";
return "mongoding";
}


Expand Down
4 changes: 3 additions & 1 deletion springboot-test/README.md
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
spring boot 学习
spring boot 学习
https://segmentfault.com/a/1190000010854811
https://www.cnblogs.com/goingforward/p/7486278.html
12 changes: 12 additions & 0 deletions springboot-test/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,18 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.3.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>


<dependency>
<groupId>org.springframework.boot</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringbootHttpApplication {
public class SpringbootApplication {

private static final Logger LOGGER = LoggerFactory.getLogger(SpringbootHttpApplication.class);
private static final Logger LOGGER = LoggerFactory.getLogger(SpringbootApplication.class);


public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(SpringbootHttpApplication.class, args);
ApplicationContext ctx = SpringApplication.run(SpringbootApplication.class, args);


}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package org.spring.springboot.dto;


import java.io.Serializable;

public class ResponseDTO<T> implements Serializable {


private static final long serialVersionUID = 1L;

private boolean success;

private int code;

private String msg;

private T data;

public ResponseDTO() {
}

public ResponseDTO(int code, String msg, T data) {
super();
this.code = code;
this.msg = msg;
this.data = data;
}


public ResponseDTO(boolean success, int code, String msg, T data) {
super();
this.success = success;
this.code = code;
this.msg = msg;
this.data = data;
}


/**
* 成功结果 (code="1",msg="",data=data)
*
* @param data
* @return
*/
public static <R> ResponseDTO<R> success(R data, String msg) {
ResponseDTO<R> result = new ResponseDTO<R>();
result.setSuccess(true);
result.setCode(1);
result.setMsg(msg);
result.setData(data);
return result;
}

public static <R> ResponseDTO<R> success(R data) {

return success(data, null);
}

public static <R> ResponseDTO<R> success() {
return success(null);
}

/**
* 失败结果
*
* @param code
* @param msg
* @param data
* @return
*/
public static <R> ResponseDTO<R> error(int code, String msg, R data) {
ResponseDTO<R> result = new ResponseDTO<R>();
result.setSuccess(false);
result.setCode(code);
result.setMsg(msg);
result.setData(data);
return result;
}

public static <R> ResponseDTO<R> error() {

return error(null);
}

public static <R> ResponseDTO<R> error(String msg) {

return error(-1, msg);
}

public static <R> ResponseDTO<R> error(int code, String msg) {

return error(code, msg, null);
}


public boolean isSuccess() {
return success;
}

public void setSuccess(boolean success) {
this.success = success;
}

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public T getData() {
return data;
}

public void setData(T data) {
this.data = data;
}

@Override
public String toString() {
return "ResponseDTO [success=" + success + ", code=" + code + ", msg=" + msg + ", data=" + data + "]";
}


}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.spring.springboot.mvc.controller;

import org.spring.springboot.dto.ResponseDTO;
import org.spring.springboot.mvc.entity.Book;
import org.spring.springboot.mvc.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -24,17 +25,19 @@ public class BookController {
* 处理 "/book" 的 GET 请求,用来获取 Book 列表
*/
@RequestMapping(method = RequestMethod.GET)
public List<Book> getBookList() {
return bookService.findAll();
public ResponseDTO<List<Book>> getBookList() {
List<Book> books = bookService.findAll();
return ResponseDTO.success(books);
}

/**
* 获取 Book
* 处理 "/book/{id}" 的 GET 请求,用来获取 Book 信息
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Book getBook(@PathVariable Long id) {
return bookService.findById(id);
public ResponseDTO<Book> getBook(@PathVariable Long id) {
Book book = bookService.findById(id);
return ResponseDTO.success(book);
}

/**
Expand All @@ -43,26 +46,30 @@ public Book getBook(@PathVariable Long id) {
* 通过 @RequestBody 绑定实体参数,也通过 @RequestParam 传递参数
*/
@RequestMapping(value = "/create", method = RequestMethod.POST)
public Book postBook(@RequestBody Book book) {
return bookService.insertByBook(book);
public ResponseDTO<Book> postBook(@RequestBody Book book) {
Book book1 = bookService.insertByBook(book);

return ResponseDTO.success(book1);
}

/**
* 更新 Book
* 处理 "/update" 的 PUT 请求,用来更新 Book 信息
*/
@RequestMapping(value = "/update", method = RequestMethod.PUT)
public Book putBook(@RequestBody Book book) {
return bookService.update(book);
public ResponseDTO<Book> putBook(@RequestBody Book book) {
Book book1 = bookService.update(book);
return ResponseDTO.success(book1);
}

/**
* 删除 Book
* 处理 "/book/{id}" 的 GET 请求,用来删除 Book 信息
*/
@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
public Book deleteBook(@PathVariable Long id) {
return bookService.delete(id);
public ResponseDTO<Book> deleteBook(@PathVariable Long id) {
Book book1 = bookService.delete(id);
return ResponseDTO.success(book1);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package org.spring.springboot;

import org.junit.Before;
import org.junit.Test;
import org.spring.springboot.mvc.controller.BookController;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.hamcrest.CoreMatchers.equalTo;

public class BookControllerMockTest {

private MockMvc mvc; //初始化执行

@Before
public void setUp() {
mvc = MockMvcBuilders.standaloneSetup(new BookController()).build();
}

//验证controller是否正常响应并打印返回结果
@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello")
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
}

//验证controller是否正常响应并判断返回结果是否正确
@Test
public void testHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello")
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string(equalTo("Hello World")));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package org.spring.springboot;

import org.junit.Assert;
import org.junit.Test;
import org.spring.springboot.dto.ResponseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.HashMap;
import java.util.Map;

public class BookControllerTest {

@Autowired
private TestRestTemplate testRestTemplate;

@Test
public void get() {
Map<String, String> multiValueMap = new HashMap<>();
multiValueMap.put("username", "lake");//传值,但要在url上配置相应的参数
ResponseDTO result = testRestTemplate.getForObject("/test/get?username={username}", ResponseDTO.class, multiValueMap);
Assert.assertEquals(result.getCode(), 0);
}

@Test
public void post() {
MultiValueMap multiValueMap = new LinkedMultiValueMap();
multiValueMap.add("username", "lake");
ResponseDTO result = testRestTemplate.postForObject("/test/post", multiValueMap, ResponseDTO.class);
Assert.assertEquals(result.getCode(), 0);
}


@Test
public void getHeader() {
HttpHeaders headers = new HttpHeaders();
headers.set("token", "xxxxxx");
HttpEntity formEntity = new HttpEntity(headers);
String[] urlVariables = new String[]{"admin"};
ResponseEntity<ResponseDTO> result = testRestTemplate.exchange("/test/getHeader?username={username}", HttpMethod.GET, formEntity, ResponseDTO.class, urlVariables);
Assert.assertEquals(result.getBody().getCode(), 0);
}

@Test
public void putHeader() {
HttpHeaders headers = new HttpHeaders();
headers.set("token", "xxxxxx");
MultiValueMap multiValueMap = new LinkedMultiValueMap();
multiValueMap.add("username", "lake");
HttpEntity formEntity = new HttpEntity(multiValueMap, headers);
ResponseEntity<ResponseDTO> result = testRestTemplate.exchange("/test/putHeader", HttpMethod.PUT, formEntity, ResponseDTO.class);
Assert.assertEquals(result.getBody().getCode(), 0);
}

@Test
public void delete() {
HttpHeaders headers = new HttpHeaders();
headers.set("token", "xxxxx");
MultiValueMap multiValueMap = new LinkedMultiValueMap();
multiValueMap.add("username", "lake");
HttpEntity formEntity = new HttpEntity(multiValueMap, headers);
String[] urlVariables = new String[]{"admin"};
ResponseEntity<ResponseDTO> result = testRestTemplate.exchange("/test/delete?username={username}", HttpMethod.DELETE, formEntity, ResponseDTO.class, urlVariables);
Assert.assertEquals(result.getBody().getCode(), 0);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package org.spring.springboot;

import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableAutoConfiguration
public class TestSpringBoot {


}
Loading

0 comments on commit 555b6cf

Please sign in to comment.