jobob 9 gadi atpakaļ
vecāks
revīzija
5bae044317

+ 1 - 0
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/framework/RestResponse.java

@@ -35,4 +35,5 @@ public class RestResponse<T> {
 	public void setData(T data) {
 		this.data = data;
 	}
+
 }

+ 48 - 27
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/framework/UserController.java

@@ -2,9 +2,13 @@ package com.baomidou.mybatisplus.test.framework;
 
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
 
 import com.baomidou.mybatisplus.test.framework.service.IUserService;
+import com.baomidou.mybatisplus.test.mysql.entity.User;
 
 @Controller
 @RequestMapping("/user")
@@ -13,31 +17,48 @@ public class UserController {
 	@Autowired
 	private IUserService userService;
 
-//	@ResponseBody
-//	@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json")
-//	public RestResponse<User> getUser(@PathVariable("id") int id) {
-//		User user = userService.getUser(id);
-//		return new RestResponse<User>(true, "", user);
-//	}
-//
-//	@ResponseBody
-//	@RequestMapping(method = RequestMethod.POST, produces = "application/json")
-//	public RestResponse saveUser(@RequestBody User user) {
-//		userService.saveUser(user);
-//		return new RestResponse<String>(true, "", null);
-//	}
-//
-//	@ResponseBody
-//	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "application/json")
-//	public RestResponse deleteUser(@PathVariable("id") int id) {
-//		userService.deleteUser(id);
-//		return new RestResponse<String>(true, "", null);
-//	}
-//
-//	@ResponseBody
-//	@RequestMapping(method = RequestMethod.PUT, produces = "application/json")
-//	public RestResponse updateUser(@RequestBody User user) {
-//		userService.updateUser(user);
-//		return new RestResponse<String>(true, "", null);
-//	}
+	@ResponseBody
+	@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json")
+	public RestResponse<User> getUser(@PathVariable("id") Long id) {
+		User user = userService.selectById(id);
+		return retRestResponse(user);
+	}
+
+	//
+	// @ResponseBody
+	// @RequestMapping(method = RequestMethod.POST, produces =
+	// "application/json")
+	// public RestResponse saveUser(@RequestBody User user) {
+	// userService.saveUser(user);
+	// return new RestResponse<String>(true, "", null);
+	// }
+	//
+	// @ResponseBody
+	// @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces
+	// = "application/json")
+	// public RestResponse deleteUser(@PathVariable("id") int id) {
+	// userService.deleteUser(id);
+	// return new RestResponse<String>(true, "", null);
+	// }
+	//
+	// @ResponseBody
+	// @RequestMapping(method = RequestMethod.PUT, produces =
+	// "application/json")
+	// public RestResponse updateUser(@RequestBody User user) {
+	// userService.updateUser(user);
+	// return new RestResponse<String>(true, "", null);
+	// }
+
+	public RestResponse<User> retRestResponse() {
+		return retRestResponse(null);
+	}
+
+	public RestResponse<User> retRestResponse(User user) {
+		return retRestResponse("", user);
+	}
+
+	public RestResponse<User> retRestResponse(String message, User user) {
+		return new RestResponse<User>(true, message, user);
+	}
+
 }

+ 49 - 35
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/framework/UserControllerTest.java

@@ -1,28 +1,54 @@
 package com.baomidou.mybatisplus.test.framework;
 
+import static org.hamcrest.Matchers.is;
+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.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+
+import java.nio.charset.Charset;
+
 import org.junit.Before;
+import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.InjectMocks;
 import org.mockito.MockitoAnnotations;
 import org.mockito.Spy;
+import org.springframework.http.MediaType;
 import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestExecutionListeners;
 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
+import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
 import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
 
 import com.baomidou.mybatisplus.test.framework.service.IUserService;
+import com.baomidou.mybatisplus.test.mysql.entity.User;
 
 /*
  * Retrieve user with ID=3: GET http://localhost:8080/user/3
-Save a new User: POST http://localhost:8080/user
-Update User: PUT http://localhost:8080/user
-Delete use with ID=3: DELETE http://localhost:8080/user/3
-
+ * Save a new User: POST http://localhost:8080/user
+ * Update User: PUT http://localhost:8080/user
+ * Delete use with ID=3: DELETE http://localhost:8080/user/3
  */
 @RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration({ "classpath:spring-test-context.xml", "classpath:mockTestBeans.xml" })
+@ContextConfiguration(locations = { "classpath:mysql/spring-test-context.xml" })
+
+/*
+ * 事务配置<br>
+ * DependencyInjectionTestExecutionListener 监听测试类中的依赖注入是否正确<br>
+ * TransactionalTestExecutionListener 监听测试类中的事务<br>
+ */
+@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class,
+		TransactionalTestExecutionListener.class })
+//@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
 public class UserControllerTest {
 
+	public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(),
+			MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
+
 	@InjectMocks
 	private UserController userController;
 
@@ -33,40 +59,28 @@ public class UserControllerTest {
 
 	@Before
 	public void setup() {
-		// this must be called for the @Mock annotations above to be processed
-		// and for the mock service to be injected into the controller under
-		// test.
 		MockitoAnnotations.initMocks(this);
 		mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
 	}
 
-	// @Test
-	// public void testGet() throws Exception {
-	//
-	// int userId = 3;
-	//
-	// mockMvc.perform(
-	// get("/user/" + userId))
-	// .andExpect(MockMvcResultMatchers.status().isOk())
-	// .andExpect(content().contentType(MediaType.APPLICATION_JSON))
-	// .andExpect(jsonPath("data.age", is(15)))
-	// .andExpect(jsonPath("data.firstName", is("bob")))
-	// .andExpect(jsonPath("data.id", is(userId)))
-	// .andExpect(jsonPath("success", is(true)));
-	// }
-	//
-	// @Test
-	// public void testSave() throws Exception {
-	// mockMvc.perform(
-	// post("/user")
-	// .contentType(TestUtil.APPLICATION_JSON_UTF8)
-	// .content(TestUtil.convertObjectToJsonBytes(new User()))
-	// )
-	// .andExpect(MockMvcResultMatchers.status().isOk())
-	// .andExpect(content().contentType(MediaType.APPLICATION_JSON))
-	// .andExpect(jsonPath("success", is(true)));
-	// }
-	//
+	@Test
+	public void testSave() throws Exception {
+		mockMvc.perform(post("/user").contentType(APPLICATION_JSON_UTF8).content(new User().toString()))
+				.andExpect(MockMvcResultMatchers.status().isOk())
+				.andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("success", is(true)));
+	}
+
+	@Test
+	public void testGet() throws Exception {
+
+		int userId = 3;
+
+		mockMvc.perform(get("/user/" + userId)).andExpect(MockMvcResultMatchers.status().isOk())
+				.andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("data.age", is(15)))
+				.andExpect(jsonPath("data.firstName", is("bob"))).andExpect(jsonPath("data.id", is(userId)))
+				.andExpect(jsonPath("success", is(true)));
+	}
+
 	// @Test
 	// public void testUpdate() throws Exception {
 	// mockMvc.perform(

+ 10 - 0
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/framework/service/UserServiceImpl.java

@@ -1,6 +1,7 @@
 package com.baomidou.mybatisplus.test.framework.service;
 
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
 
 import com.baomidou.framework.service.impl.SuperServiceImpl;
 import com.baomidou.mybatisplus.test.mysql.UserMapper;
@@ -9,4 +10,13 @@ import com.baomidou.mybatisplus.test.mysql.entity.User;
 @Service
 public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implements IUserService {
 	
+	/**
+	 * 测试事务
+	 */
+	@Transactional
+	@Override
+	public boolean insert(User entity) {
+		return super.insert(entity);
+	}
+	
 }

+ 1 - 1
mybatis-plus/src/test/resources/mysql/mysql.sql

@@ -41,6 +41,6 @@ CREATE TABLE `user` (
   `role` bigint(20) DEFAULT NULL,
   `phone` varchar(64) COLLATE utf8_bin DEFAULT NULL,
   PRIMARY KEY (`test_id`)
-) ENGINE=MyISAM AUTO_INCREMENT=774164658700161025 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='用户表';
+) ENGINE=InnoDB AUTO_INCREMENT=774164658700161025 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='用户表';
 
 SET FOREIGN_KEY_CHECKS = 1;

+ 49 - 0
mybatis-plus/src/test/resources/mysql/spring-test-context.xml

@@ -0,0 +1,49 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
+	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
+	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
+	xsi:schemaLocation="
+     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
+     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
+     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
+     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
+
+	<context:component-scan
+		base-package="com.baomidou.mybatisplus.test.framework.service" />
+
+	<!-- 配置DataSource数据源 -->
+	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
+		destroy-method="close">
+		<property name="driverClassName" value="${driverClass}" />
+		<property name="url" value="${jdbcUrl}" />
+		<property name="username" value="${user}" />
+		<property name="password" value="${password}" />
+		<property name="maxActive" value="50" />
+		<property name="maxIdle" value="3" />
+		<property name="maxWait" value="1000" />
+		<property name="defaultAutoCommit" value="true" />
+		<property name="removeAbandoned" value="true" />
+		<property name="removeAbandonedTimeout" value="60" />
+	</bean>
+
+	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
+		<property name="dataSource" ref="dataSource" />
+		<property name="mapperLocations" value="classpath:mysql/*Mapper.xml" />
+	</bean>
+
+	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
+		p:basePackage="com.baomidou.mybatisplus.test.mysql"
+		p:sqlSessionFactoryBeanName="sqlSessionFactory" />
+
+	<!-- 对dataSource 数据源进行事务管理 -->
+	<bean id="transactionManager"
+		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
+		<property name="dataSource" ref="dataSource" />
+	</bean>
+
+	<!-- 开启事务注解驱动 -->
+	<tx:annotation-driven transaction-manager="transactionManager" />
+
+</beans>

+ 0 - 15
mybatis-plus/src/test/resources/spring-test-context.xml

@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<beans:beans xmlns="http://www.springframework.org/schema/mvc"
-             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-             xmlns:beans="http://www.springframework.org/schema/beans"
-             xmlns:context="http://www.springframework.org/schema/context"
-             xmlns:mvc="http://www.springframework.org/schema/task"
-             xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
-		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
-		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
-
-    <mvc:annotation-driven/>
-
-    <context:component-scan base-package="com.baomidou.mybatisplus.test"/>
-
-</beans:beans>