• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >Java > Junit4测试Controller

Junit4测试Controller

作者:Java兔的博客 字体:[增加 减小] 来源:互联网 时间:2017-08-23

Java兔的博客通过本文主要向大家介绍了junit,测试等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

使用注入controller的方式测试controller接口

Controller层

/**
 * 组织机构管理的处理
 */
@Controller
@RequestMapping("/system/dept")
public class DeptController {
    /**
     * 组织机构管理服务
     */
    @Autowired
    private DeptService deptService;

    /**
     * 权限管理服务
     */
    @Autowired
    private AuthorService authorService;

    /**
     * 组织机构管理页面入口
     * @return 跳转到组织机构管理页面
     */
    @RequestMapping("/show")
    public String show(ModelMap map, String menuId, HttpServletRequest request) {
        //得到用户信息
        UserInfo users = Util.getSessionUserInfo(request);
        //保存当前用户的所属区域
        map.put("regionCode", users.getRegionCode());
        //得到操作权限
        Map<String, String> operation = authorService.getOperPermission(users.getRoleIdList(), menuId);
        map.put("operation", operation);
        return "system/organization/organizationList";
    }
}   

单元测试类

package com.wx.app.ygp.action.system;

import com.wx.app.ygp.entity.system.UserInfo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author huangjp
 * @create in 2017-8-23 13:45
 * @Description : 部门管理控制层的测试类
 **/
@RunWith(SpringJUnit4ClassRunner.class) //这个必须使用junit4.9以上才有
@ContextConfiguration(locations = {"classpath:spring-test.xml","classpath:spring-mybatis.xml"})
@TransactionConfiguration(defaultRollback=true) //配置事务的回滚,对数据库的增删改都会回滚,便于测试用例的循环利用
@Transactional  //事务处理
public class DeptControllerTest extends AbstractTransactionalJUnit4SpringContextTests {

    //mock模拟session
    private MockHttpSession session;

    //mock模拟request
    private MockHttpServletRequest request;

    @Before
    public void setUp() throws Exception {

        this.session = new MockHttpSession();
        this.request = new MockHttpServletRequest();

    }

    @Test
    public void testShow() throws Exception {

        //创建参数
        UserInfo userInfo = new UserInfo();
        userInfo.setRegionCode("360482");
        List<String> roleIdList = new ArrayList<>();
        roleIdList.add("2410151");
        userInfo.setRoleIdList(roleIdList);
        session.setAttribute("userInfo",userInfo);
        ModelMap modelMap = new ModelMap();
        request.setSession(session);
        String menuId = "21";

        //构造controller
        DeptController deptController = (DeptController) this.applicationContext.getBean("deptController");
        String result = deptController.show(modelMap, menuId, request);

        System.out.println("返回值:" + result);

    }
}

spring-test.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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache-3.2.xsd ">

    <!-- 配置资源文件 --> 
    <bean id="ygpProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
             <list>
                 <value>classpath:db.properties</value>
             </list>
        </property>
     </bean>
     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
          <property name="properties" ref="ygpProperties" />
     </bean>

    <!-- 配置数据库 -->  
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="${base.url}"/>
        <property name="username" value="${base.username}"/>
        <property name="password" value="${base.password}"/>
        <property name="driverClassName" value="${base.driver}"/>
    </bean>

    <!-- 配置需要测试的controller -->
    <bean id="deptController" class="com.wx.app.ygp.action.system.DeptController"></bean>
    <!-- 配置controller中需要注入的service(无论此次测试的接口是否要使用,都需要配置进来,否则会报加载配置文件失败的错误)-->
    <bean id="authorService" class="com.wx.app.ygp.service.system.impl.AuthorServiceImpl"></bean>
    <bean id="rolePrivilegeService" class="com.wx.app.ygp.service.privilege.impl.RolePrivilegeServiceImpl"></bean>
    <bean id="deptService" class="com.wx.app.ygp.service.system.impl.DeptServiceImpl"></bean>
</beans>

spring-mybatis.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"
       default-lazy-init="true"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <description>Mybatis Configuration</description>

    <!-- Mybatis begin -->
    <!--  事务管理配置 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 与mybatis集成  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!-- mybatis配置文件自动扫描路径  -->
        <property name="mapperLocations" value="classpath:com/wx/app/ygp/**/dao/*.xml"></property>
    </bean>

    <!-- Mapper接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wx.app.ygp.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
    <!-- Mybatis end -->
    <bean id="jdbcTemplate"
        class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
    </bean>

    <bean id="idGenarater"
        class="org.springframework.jdbc.support.incrementer.MySQLMaxValueIncrementer">
        <property name="incrementerName" value="ss_key_table"/> 
        <property name="columnName" value="sequence"/>
        <property name="cacheSize" value="2"/> 
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

测试结果

返回值:system/organization/organizationList

参考资料

  • Spring自带mock测试Controller

结语

使用mockmvc测试controller时,显示authorService为null,即service注入失败,不知道是什么原因引起的,待解决。

分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • Junit4测试Controller
  • 详解Java单元测试Junit框架实例
  • 详解Java单元测试Junit框架实例

相关文章

  • 2017-05-28解决Java原生压缩组件不支持中文文件名乱码的问题
  • 2017-05-28HashMap和Hashtable的详细比较
  • 2017-05-28springmvc fastjson 反序列化时间格式化方法(推荐)
  • 2017-05-28java Socket实现简单模拟HTTP服务器
  • 2017-05-28浅谈Java中注解Annotation的定义、使用、解析
  • 2017-05-28java 对文件夹目录进行深度遍历实例代码
  • 2017-05-28Java内部类_动力节点Java学院整理
  • 2017-05-28Spring MVC 4.1.3 + MyBatis零基础搭建Web开发框架(注解模式)
  • 2017-05-28Java 字符串连接的性能问题分析
  • 2017-05-28Java解析Excel文件并把数据存入数据库

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • Java 泛型总结(二):泛型与数组
    • java集合遍历的几种方式总结及详细比较
    • 浅谈Java中注解Annotation的定义、使用、解析
    • Java LocalCache 本地缓存的实现实例
    • Java的内存机制详解
    • Spring boot学习教程之快速入门篇
    • 详谈java 堆区、方法区和栈区
    • java 中 System.out.println()和System.out.write()的区别
    • Java equals 方法与hashcode 方法的深入解析
    • SpringBoot连接MYSQL数据库并使用JPA进行操作

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有