关于spring mvc+mybatis+junit单元测试

这次测试的目的是直接在单元测试中测试Controller的类。

在单元测试的时候一定要保证spring部分和mybatis部分的代码编写全部正确,即便是没有用到的一些bean和一些mybatis的增删改查。junit会扫描全部的内容,遇到扫描错误的就会报出。

先看applicationContext文件

<?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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:p="http://www.springframework.org/schema/p" 
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">



	<import resource="classpath:spring/service.xml"/>
	<!-- <context:annotation-config /> -->
	
<!-- 	<context:component-scan base-package="com.ewell.home" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
		<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
	</context:component-scan>
	-->
	<mvc:annotation-driven>
		<mvc:message-converters register-defaults="true">
			<bean class="org.springframework.flex.http.AmfHttpMessageConverter"/>
		</mvc:message-converters>
	</mvc:annotation-driven> 

	<!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
	<context:component-scan base-package="com.ewell">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
		<context:exclude-filter type="annotation"
			expression="org.springframework.web.bind.annotation.ControllerAdvice" />
	</context:component-scan>
	
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" >
			<value>classpath:datasource.properties</value>
		</property>
	</bean>

	<!-- SqlServer数据源配置 -->
	<bean id="dataSource" class="org.apache.ibatis.datasource.unpooled.UnpooledDataSource">
		<property name="driver" value="${jdbc-2.proxool.driver-class}" />
		<property name="url" value="${jdbc-2.proxool.driver-url}" />
		<property name="username" value="${jdbc-2.user}" />
		<property name="password" value="${jdbc-2.password}" />
	</bean>
	
	<!-- SqlServer配置 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:mybatis/mybatis-sqlserver.xml" />
		<property name="mapperLocations" value="classpath*:com/ewell/home/mapper/*.xml"/>
	</bean>
	
	<bean id="myBatisDAO" class="com.ewell.isd.mybatis.dao.MyBatisDAO">
		<property name="sqlSessionFactory" ref="sqlSessionFactory" />
	</bean>

	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<bean id="nameMatch" class="org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource">
		<property name="properties">
			<props>
				<prop key="*">PROPAGATION_REQUIRED</prop>
			</props>
		</property>
	</bean>
	<bean id="methodCallLogInterceptor" class="com.ewell.isd.spring.interceptor.MethodCallLogInterceptor" />

	<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
		<property name="transactionManager">
			<ref local="transactionManager" />
		</property>
		<property name="transactionAttributeSource">
			<ref local="nameMatch"/>
		</property>
	</bean>
	
	<bean id="autoProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
		<property name="beanNames">
			<list>
				<value>*Service</value>
			</list>
		</property>
		<property name="interceptorNames">
			<list>
				<idref local="transactionInterceptor"/> 
				<!-- <idref local="transactionInterceptor_sqlServerL"/> -->
			</list>
		</property>
	</bean>
	


	<!-- Nothing real usage -->
	<bean id="SpringContextUtil" class="com.ewell.zonghe.configration.SpringContextUtil "/>
</beans>
mybatis-sqlserver.xml文件

<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE configuration 
  PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" 
  "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
<configuration>
	<settings>
		<setting name="cacheEnabled" value="true" />
	</settings>
	<plugins>
		<plugin interceptor="com.ewell.isd.mybatis.plugin.SelectCountSqlInterceptor"/>  		 
		<plugin interceptor="com.ewell.sqlserverDialect.SqlServerInterceptor">		
			<property name="dialectClass" value="com.ewell.sqlserverDialect.SqlServerDialect"/>			
		</plugin>
	
	</plugins>
	
</configuration>

spring-servlet.xml文件

<?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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

	<!-- 自动扫描且只扫描@Controller -->
	<context:component-scan base-package="com.ewell"
		use-default-filters="false">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
		<context:include-filter type="annotation"
			expression="org.springframework.web.bind.annotation.ControllerAdvice" />
	</context:component-scan>

	<!-- 加载注解驱动 -->


	<mvc:annotation-driven />

	<!-- 定义JSP文件的位置 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/test/" />
		<property name="suffix" value=".html" />
	</bean>
	<!-- 容器默认的DefaultServletHandler处理 所有静态内容与无RequestMapping处理的URL -->
	<mvc:default-servlet-handler />
	<!-- 将Controller抛出的异常转到特定View, 保持SiteMesh的装饰效果 -->
	<bean
		class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<props>
				<prop key="java.lang.Throwable">error/500</prop>
			</props>
		</property>
	</bean>



</beans>

Controller部分:TestController.java

package com.ewell.home.controller;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ewell.home.service.UserService;
import com.ewell.home.vo.User;

@Controller
@RequestMapping("/TestController")
public class TestController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/getUser")
	@ResponseBody
	public String getUser(String id){
		String massage = "";
		Map<String,Object> map = new HashMap<String,Object>();
		User user = null;
		user = userService.getUser(Integer.parseInt(id));
		
		if(null == user){
			massage = "error";
		}else{
			massage = "success";
		}
		return massage;
	}
}

ServiceImpl文件

package com.ewell.home.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ewell.home.service.UserService;
import com.ewell.home.vo.User;
import com.ewell.isd.mybatis.dao.MyBatisDAO;

@Service
public class UserServiceImpl implements UserService{
	@Autowired
	private MyBatisDAO myBatisDAO;
	
	@Override
	public User getUser(Integer id) {
		// TODO Auto-generated method stub
		return (User)myBatisDAO.findForObject("getUser",id);
	}
}

单元测试部分

基类BaseSpringTestCase

package com.ewell;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

	@RunWith(SpringJUnit4ClassRunner.class)
	@ContextConfiguration(locations={"classpath:applicationContext.xml"})

	// 添加注释@Transactional 回滚对数据库操作  
	@Transactional
	public class BaseSpringTestCase {
		
	}

测试类:TestUser
package com.ewell;

import static org.junit.Assert.assertEquals;

import java.sql.SQLException;

import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

import com.ewell.home.controller.TestController;
import com.ewell.home.service.UserService;
import com.ewell.home.vo.User;


public class TestUser extends BaseSpringTestCase{
	private MockHttpServletRequest request;
	private MockHttpServletResponse response;
	private UserService userService;
	@Autowired
	private TestController testController ;
    @Before
    public void before(){                                                                   
/*        ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext.xml"
                ,"classpath:mybatis/mybatis-sqlserver.xml"});*/
        request = new MockHttpServletRequest();    
        request.setCharacterEncoding("UTF-8");    
        response = new MockHttpServletResponse();
    }
     
    @Test
    public void addUser(){
        User user = new User();
		String id= "23" ;
		assertEquals("loginok",testController.getUser(id)) ;
    }
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
基于SpringSpring MVCMyBatis的博客系统开发教程如下: 首先,要准备好开发所需的环境和工具。你需要安装Java开发工具包(JDK)、Eclipse或者IntelliJ IDEA集成开发环境、Apache Tomcat服务器、Maven构建工具以及MySQL数据库。确保这些工具都正确安装和配置。 接下来,创建一个新的Maven项目,并在pom.xml文件中添加依赖项,包括Spring MVCMyBatis、数据库连接池、日志等。这些依赖项可以通过Maven自动下载和管理。 然后,在src/main/java目录下创建相应的包结构,如controller、service、dao等。在dao包下创建相应的数据访问接口,并使用MyBatis提供的注解或XML配置文件实现数据访问的逻辑。在service包下创建对应的服务接口和实现类,用于处理业务逻辑。在controller包下创建控制器类,处理请求和响应。 配置SpringMyBatis的配置文件。在src/main/resources目录下创建一个名为applicationContext.xml的Spring配置文件,并添加相关的配置信息,包括数据库连接、事务管理、包扫描等。同样,在该目录下创建一个名为mybatis-config.xml的MyBatis配置文件,并配置数据源、映射文件等。 编写博客系统的前端页面和样式。可以使用HTML、CSS和JavaScript等技术来构建用户界面,使用JSP或Thymeleaf等模板引擎来动态生成页面内容。可以使用Bootstrap等前端框架来加快开发进度并提供良好的用户体验。 最后,测试和部署博客系统。使用JUnit单元测试框架来测试各个模块的功能是否正常。将项目打包成war文件,并将其部署到Tomcat服务器上运行。 通过以上步骤,你就可以基于SpringSpring MVCMyBatis来开发一个简单的博客系统了。当然,在实际开发中还会涉及到更多的细节和技术选择,需要持续学习和实践。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值