Junit 4テストコントローラ


前言
コントローラインタフェースを注入する方法でテストする
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 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 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

<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.propertiesvalue>
             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>

    
    <bean id="deptController" class="com.wx.app.ygp.action.system.DeptController">bean>
    
    <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

<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 Configurationdescription>

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

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource">property>
        <property name="configLocation" value="classpath:mybatis-config.xml">property>
        
        <property name="mapperLocations" value="classpath:com/wx/app/ygp/**/dao/*.xml">property>
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wx.app.ygp.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>
    bean>
    
    <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、すなわちサービス注入に失敗したことが表示され、何が原因で起こったのか、解決しなければならない.