From b107d49da325dc4e5799d60bbeacb0522042f822 Mon Sep 17 00:00:00 2001 From: bwh Date: Mon, 15 Apr 2019 23:14:57 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=E7=AB=A0=E8=8A=824=E5=8D=95?= =?UTF-8?q?=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pom.xml | 1 - .../core/ValidatingFormInputApplication.java | 36 +++- .../java/spring/boot/core/domain/User.java | 9 + .../spring/boot/core/web/UserController.java | 2 +- .../src/main/resources/application.properties | 15 +- .../boot/core/web/UserControllerTest.java | 159 ++++++++++++++++++ .../src/test/resources/application.properties | 14 ++ .../src/test/resources/static/css/default.css | 2 + .../test/resources/static/images/favicon.ico | Bin 0 -> 946 bytes .../test/resources/templates/userForm.html | 58 +++++++ .../test/resources/templates/userList.html | 46 +++++ 11 files changed, 335 insertions(+), 7 deletions(-) create mode 100644 chapter-4-spring-boot-validating-form-input/src/test/java/spring/boot/core/web/UserControllerTest.java create mode 100644 chapter-4-spring-boot-validating-form-input/src/test/resources/application.properties create mode 100755 chapter-4-spring-boot-validating-form-input/src/test/resources/static/css/default.css create mode 100755 chapter-4-spring-boot-validating-form-input/src/test/resources/static/images/favicon.ico create mode 100644 chapter-4-spring-boot-validating-form-input/src/test/resources/templates/userForm.html create mode 100644 chapter-4-spring-boot-validating-form-input/src/test/resources/templates/userList.html diff --git a/chapter-4-spring-boot-validating-form-input/pom.xml b/chapter-4-spring-boot-validating-form-input/pom.xml index 2c63471..ef6e623 100644 --- a/chapter-4-spring-boot-validating-form-input/pom.xml +++ b/chapter-4-spring-boot-validating-form-input/pom.xml @@ -54,7 +54,6 @@ com.h2database h2 - runtime diff --git a/chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/ValidatingFormInputApplication.java b/chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/ValidatingFormInputApplication.java index 1825f04..c6cb5ac 100644 --- a/chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/ValidatingFormInputApplication.java +++ b/chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/ValidatingFormInputApplication.java @@ -1,12 +1,40 @@ package spring.boot.core; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import spring.boot.core.domain.User; +import spring.boot.core.domain.UserRepository; @SpringBootApplication -public class ValidatingFormInputApplication { +public class ValidatingFormInputApplication implements CommandLineRunner { - public static void main(String[] args) { - SpringApplication.run(ValidatingFormInputApplication.class, args); - } + + private Logger LOG = LoggerFactory.getLogger(ValidatingFormInputApplication.class); + + @Autowired + private UserRepository userRepository; + + public static void main(String[] args) { + SpringApplication.run(ValidatingFormInputApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + User user1 = new User("Sergey", 24, "1994-01-01"); + User user2 = new User("Ivan", 26, "1994-01-01"); + User user3 = new User("Adam", 31, "1994-01-01"); + LOG.info("Inserting data in DB."); + userRepository.save(user1); + userRepository.save(user2); + userRepository.save(user3); + LOG.info("User count in DB: {}", userRepository.count()); + LOG.info("User with ID 1: {}", userRepository.findById(1L)); + LOG.info("Deleting user with ID 2L form DB."); + userRepository.deleteById(2L); + LOG.info("User count in DB: {}", userRepository.count()); + } } diff --git a/chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/domain/User.java b/chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/domain/User.java index 535d3a5..45d4aaf 100644 --- a/chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/domain/User.java +++ b/chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/domain/User.java @@ -79,6 +79,15 @@ public class User implements Serializable { this.birthday = birthday; } + + public User(String name, Integer age, String birthday) { + this.name = name; + this.age = age; + this.birthday = birthday; + } + + public User() {} + @Override public String toString() { return "User{" + diff --git a/chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/web/UserController.java b/chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/web/UserController.java index 3eb0360..8a51c84 100644 --- a/chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/web/UserController.java +++ b/chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/web/UserController.java @@ -103,7 +103,7 @@ public class UserController { /** * 处理 "/users/{id}" 的 GET 请求,用来删除 User 信息 */ - @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) + @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { userService.delete(id); diff --git a/chapter-4-spring-boot-validating-form-input/src/main/resources/application.properties b/chapter-4-spring-boot-validating-form-input/src/main/resources/application.properties index 51350c6..1a47991 100644 --- a/chapter-4-spring-boot-validating-form-input/src/main/resources/application.properties +++ b/chapter-4-spring-boot-validating-form-input/src/main/resources/application.properties @@ -1,2 +1,15 @@ +## 开启 H2 数据库 +spring.h2.console.enabled=true + +## 配置 H2 数据库连接信息 +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= + + + ## 是否显示 SQL 语句 -spring.jpa.show-sql=true \ No newline at end of file +spring.jpa.show-sql=true +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.hbm2ddl.auto=create diff --git a/chapter-4-spring-boot-validating-form-input/src/test/java/spring/boot/core/web/UserControllerTest.java b/chapter-4-spring-boot-validating-form-input/src/test/java/spring/boot/core/web/UserControllerTest.java new file mode 100644 index 0000000..08e9af7 --- /dev/null +++ b/chapter-4-spring-boot-validating-form-input/src/test/java/spring/boot/core/web/UserControllerTest.java @@ -0,0 +1,159 @@ +package spring.boot.core.web; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.context.TestPropertySource; +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.result.MockMvcResultMatchers; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import spring.boot.core.ValidatingFormInputApplication; +import spring.boot.core.domain.User; +import spring.boot.core.service.UserService; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Collection; +import java.util.Map; + +import static junit.framework.TestCase.assertNotNull; +import static junit.framework.TestCase.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; +import static org.junit.Assert.assertEquals; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = ValidatingFormInputApplication.class) +@AutoConfigureMockMvc +@TestPropertySource(locations = "classpath:application.properties") +public class UserControllerTest { + + + @Autowired + private MockMvc mockMvc; + + @Autowired + private UserService userService; + + @Autowired + private ObjectMapper objectMapper; + + @Test + public void getUserList() throws Exception { + mockMvc.perform(get("/users")) + .andExpect(view().name("userList")) + .andExpect(status().isOk()) + .andDo(print()); + } + + private User createUser() { + User user = new User(); + user.setName("测试用户"); + user.setAge(100); + user.setBirthday("1994-01-01"); + return userService.insertByUser(user); + } + + @Test + public void createUserForm() throws Exception { + + mockMvc.perform(get("/users/create")) + .andDo(print()) + .andExpect(view().name("userForm")) + .andExpect(request().attribute("action", "create")) + .andDo(print()) + .andReturn(); + } + + @Test + public void postUser() throws Exception { + User user = createUser(); + assertNotNull(user); + + MultiValueMap parameters = new LinkedMultiValueMap(); + Map maps = objectMapper.convertValue(user, new TypeReference>() { + }); + parameters.setAll(maps); + + mockMvc.perform(post("/users/create").params(parameters)) + .andDo(print()) + .andExpect(status().is(HttpServletResponse.SC_FOUND)) + .andDo(print()) + .andExpect(view().name("redirect:/users/")) + .andDo(print()) + .andReturn(); + } + + @Test + public void getUser() throws Exception { + + MvcResult result= mockMvc.perform(get("/users/update/{id}/", 1)) + .andExpect(status().isOk()) + .andExpect(view().name("userForm")) + .andExpect(MockMvcResultMatchers.model().attributeExists("action")) + .andExpect(model().attribute("user", hasProperty("id", is(1L)))) + .andExpect(model().attribute("user", hasProperty("name", is("Sergey")))) + .andExpect(model().attribute("user", hasProperty("age", is(24)))) + .andExpect(model().attribute("user", hasProperty("birthday", is("1994-01-01")))) + .andReturn(); + + + MockHttpServletResponse mockResponse=result.getResponse(); + assertThat(mockResponse.getContentType()).isEqualTo("text/html;charset=UTF-8"); + + Collection responseHeaders = mockResponse.getHeaderNames(); + assertNotNull(responseHeaders); + assertEquals(2, responseHeaders.size()); + assertEquals("Check for Content-Type header", "Accept-Language", responseHeaders.iterator().next()); + String responseAsString=mockResponse.getContentAsString(); + assertTrue(responseAsString.contains("用户管理")); + } + + @Test + public void putUser() throws Exception { + User user = createUser(); + assertNotNull(user); + + MultiValueMap parameters = new LinkedMultiValueMap(); + Map maps = objectMapper.convertValue(user, new TypeReference>() { + }); + parameters.setAll(maps); + + mockMvc.perform(post("/users/update").params(parameters)) + .andDo(print()) + .andExpect(status().is(HttpServletResponse.SC_FOUND)) + .andDo(print()) + .andExpect(view().name("redirect:/users/")) + .andDo(print()) + .andReturn(); + } + + @Test + public void deleteUser() throws Exception { + mockMvc.perform( MockMvcRequestBuilders.delete("/users/delete/{id}", 1L) ) + .andDo(print()) + .andExpect(status().is(HttpServletResponse.SC_FOUND)) + .andExpect(view().name("redirect:/users/")); + } + + public static byte[] convertObjectToJsonBytes(Object object) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + return mapper.writeValueAsBytes(object); + } +} \ No newline at end of file diff --git a/chapter-4-spring-boot-validating-form-input/src/test/resources/application.properties b/chapter-4-spring-boot-validating-form-input/src/test/resources/application.properties new file mode 100644 index 0000000..893718a --- /dev/null +++ b/chapter-4-spring-boot-validating-form-input/src/test/resources/application.properties @@ -0,0 +1,14 @@ +## 开启 H2 数据库 +spring.h2.console.enabled=true + +## 配置 H2 数据库连接信息 +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= + + +## 是否显示 SQL 语句 +spring.jpa.show-sql=true +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.hbm2ddl.auto=create diff --git a/chapter-4-spring-boot-validating-form-input/src/test/resources/static/css/default.css b/chapter-4-spring-boot-validating-form-input/src/test/resources/static/css/default.css new file mode 100755 index 0000000..4da3051 --- /dev/null +++ b/chapter-4-spring-boot-validating-form-input/src/test/resources/static/css/default.css @@ -0,0 +1,2 @@ +/* contentDiv */ +.contentDiv {padding:20px 60px;} \ No newline at end of file diff --git a/chapter-4-spring-boot-validating-form-input/src/test/resources/static/images/favicon.ico b/chapter-4-spring-boot-validating-form-input/src/test/resources/static/images/favicon.ico new file mode 100755 index 0000000000000000000000000000000000000000..e5a293420da31e952b5d47660a089cee51c008e8 GIT binary patch literal 946 zcma)3O=}ZT6n*u3BXlKFT-eFXWSS<8PDNu2+6JlJbyvlW=%O24)K;WLDk+!>BGfNj zgc2)8v^I(qD_ALQGc(B~cIM5DsGBZaC?fuWVs)7(4(}VkZCQsdp&)(?oE-m!Mt)=swRKI%I$=_{v zj7-?pGpduH?)1#j-Vdb+YHX|2Ig+}dM#tkDtz#V!O7?OY-A2u_6r{D{Y34&Y1+T`cO#b+STOhD+~Sx}}1LDXM^Kn<=T zqK_`G*n>K2OfP_Q4yKPahppp34dl&1@c9HN=^+rcxlJGKPCkqL(trH24$Bo@ZQ*iT@hP%nRl+k&eev`{otLX z|FGZ<7j`?wmt$k*F=ekpsE+Zj z4qo+5!kW6ZwiyC literal 0 HcmV?d00001 diff --git a/chapter-4-spring-boot-validating-form-input/src/test/resources/templates/userForm.html b/chapter-4-spring-boot-validating-form-input/src/test/resources/templates/userForm.html new file mode 100644 index 0000000..f60c4e0 --- /dev/null +++ b/chapter-4-spring-boot-validating-form-input/src/test/resources/templates/userForm.html @@ -0,0 +1,58 @@ + + + + + + + + + 用户管理 + + + +
+ +
《 Spring Boot 2.x 核心技术实战》第二章快速入门案例
+ + + 用户管理 + + +
+ + + +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+
+    + +
+
+
+
+ + \ No newline at end of file diff --git a/chapter-4-spring-boot-validating-form-input/src/test/resources/templates/userList.html b/chapter-4-spring-boot-validating-form-input/src/test/resources/templates/userList.html new file mode 100644 index 0000000..3d680f1 --- /dev/null +++ b/chapter-4-spring-boot-validating-form-input/src/test/resources/templates/userList.html @@ -0,0 +1,46 @@ + + + + + + + + + 用户列表 + + + + +
+ +
《 Spring Boot 2.x 核心技术实战》第二章快速入门案例
+ + + + 用户列表 + + + + + + + + + + + + + + + + + + + +
用户编号名称年龄出生时间管理
删除
+ + +
+ + + \ No newline at end of file