Junit4测试Controller

莫兴言
2023-12-01

前言

使用注入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

参考资料

结语

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

 类似资料: