美文网首页软件测试学习之路
Spring集成MyBatis进行单元测试

Spring集成MyBatis进行单元测试

作者: 乘风破浪的姐姐 | 来源:发表于2018-03-20 10:16 被阅读31次

    本文主要介绍Spring集成MyBatis,并进行结合Junit进行单元测试的过程,以及在整合过程中遇到的问题。
    准备环境:
    a.操作系统 :win7 x64
    b.基本软件:MySQL,Mybatis,Intelli idea

    1.新建Maven项目,目录层级如下图


    image.png

    2、在pom.xml文件中加入整个项目需要的依赖包

     <properties>
        <java-version>1.8</java-version>
        <org.springframework-version>4.3.14.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <org.slf4j-version>1.6.6</org.slf4j-version>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${org.springframework-version}</version>
          <exclusions>
            <!-- Exclude Commons Logging in favor of SLF4j -->
            <exclusion>
              <groupId>commons-logging</groupId>
              <artifactId>commons-logging</artifactId>
            </exclusion>
          </exclusions>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
          <groupId>commons-dbutils</groupId>
          <artifactId>commons-dbutils</artifactId>
          <version>1.6</version>
        </dependency>
        <!--Mybatis+Spring整合-->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.3.2</version>
        </dependency>
        <!--mybatis依赖包-->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.4.6</version>
        </dependency>
        <dependency>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-core</artifactId>
          <version>1.3.6</version>
        </dependency>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.22</version>
        </dependency>
        <!-- AspectJ -->
        <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjrt</artifactId>
          <version>${org.aspectj-version}</version>
        </dependency>
        <!-- Logging -->
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>jcl-over-slf4j</artifactId>
          <version>${org.slf4j-version}</version>
          <scope>runtime</scope>
        </dependency>
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>${org.slf4j-version}</version>
          <scope>runtime</scope>
        </dependency>
        <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.15</version>
          <exclusions>
            <exclusion>
              <groupId>javax.mail</groupId>
              <artifactId>mail</artifactId>
            </exclusion>
            <exclusion>
              <groupId>javax.jms</groupId>
              <artifactId>jms</artifactId>
            </exclusion>
            <exclusion>
              <groupId>com.sun.jdmk</groupId>
              <artifactId>jmxtools</artifactId>
            </exclusion>
            <exclusion>
              <groupId>com.sun.jmx</groupId>
              <artifactId>jmxri</artifactId>
            </exclusion>
          </exclusions>
          <scope>runtime</scope>
        </dependency>
        <dependency>
          <groupId>javax.inject</groupId>
          <artifactId>javax.inject</artifactId>
          <version>1</version>
        </dependency>
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>4.0.0</version>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>javax.servlet.jsp</groupId>
          <artifactId>jsp-api</artifactId>
          <version>2.1</version>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
        </dependency>
        <dependency>
          <groupId>org.apache.logging.log4j</groupId>
          <artifactId>log4j-api</artifactId>
          <version>2.8.2</version>
        </dependency>
        <dependency>
          <groupId>org.apache.logging.log4j</groupId>
          <artifactId>log4j-core</artifactId>
          <version>2.8.2</version>
        </dependency>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
        </dependency>
      </dependencies>
    

    3、为了方便操作,Intelli idea 可以结合mybatis-generator-maven-plugin插件自动生成MyBatis代码。
    首先,需要在pom.xml文件的build节点下加入该插件的配置。

    <!-- mybatis-generator自动生成代码插件 -->
    <plugin>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-maven-plugin</artifactId>
      <version>1.3.6</version>
      <configuration>
        <verbose>true</verbose>
        <overwrite>true</overwrite>
      </configuration>
    </plugin>
    

    其次,要在maven项目下的src/main/resources 目录下建立名为 generatorConfig.xml的配置文件,作为mybatis-generator-maven-plugin 插件的执行目标。

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    <generatorConfiguration>
        <!-- 数据库驱动 -->
        <properties resource="jdbc.properties" />
        <!-- 指定数据连接驱动jar地址 -->
        <classPathEntry location="${driverPath}" />
        <context id="DB2Tables" targetRuntime="MyBatis3">
            <commentGenerator>
                <property name="suppressDate" value="true" />
                <!-- 是否去除自动生成的注释 true:是 : false:否 -->
                <property name="suppressAllComments" value="true" />
            </commentGenerator>
            <!--数据库链接URL,用户名、密码 -->
            <jdbcConnection driverClass="${driverClass}"
                            connectionURL="${jdbcUrl}" userId="${user}" password="${password}">
            </jdbcConnection>
    
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false" />
            </javaTypeResolver>
            <!-- 生成模型的包名和位置 -->
            <javaModelGenerator targetPackage="${target_package}.pojo"
                                targetProject=".\src\main\java">
                <property name="enableSubPackages" value="true" />
                <property name="trimStrings" value="true" />
            </javaModelGenerator>
            <!-- 生成映射文件的包名和位置 -->
            <sqlMapGenerator targetPackage="${target_package}.mapping"
                             targetProject=".\src\main\java">
                <property name="enableSubPackages" value="true" />
            </sqlMapGenerator>
            <!-- 生成DAO的包名和位置 -->
            <javaClientGenerator type="XMLMAPPER"
                                 targetPackage="${target_package}.dao" targetProject=".\src\main\java">
                <property name="enableSubPackages" value="true" />
            </javaClientGenerator>
            <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名 -->
            <table tableName="myuser" domainObjectName="User"
                   enableCountByExample="false" enableUpdateByExample="false"
                   enableDeleteByExample="false" enableSelectByExample="false"
                   selectByExampleQueryId="false">
                <property name="useActualColumnNames" value="false" />
            </table>
        </context>
    </generatorConfiguration>
    

    上述配置spring数据源,需要在src/main/resources 目录下新增Jdbc.properties文件。文件内容如下:
    注意,mysql-connector-java包的版本需要是6.0以下,否则会报错。

    user=root
    password=123
    driverClass=com.mysql.jdbc.Driver
    jdbcUrl=jdbc:mysql://192.168.100.63:3308/mysql
    driverPath=C:\\Users\\ccc\\.m2\\repository\\mysql\\mysql-connector-java\\5.1.22\\mysql-connector-java-5.1.22.jar
    target_package=com.sc
    

    要生面的表myuser,在mysql中存在,具体结构如下


    image.png

    最后在intelli IDEA 的菜单栏,点击RUN-Edit Configurations,点击弹出窗口左上角的+号,新增Maven.为当前配置配置一个名称,这里命名为"generator",然后在 “Command line” 选项中输入“mybatis-generator:generate -e”。这里加了“-e ”选项是为了让该插件输出详细信息,帮助我们定位问题。
    点击Apply。


    image.png
    image.png

    点击运行geratorator,即可自动生成dao,pojo,mapping对应文件


    image.png

    4、上述生成MyBatis相关文件后,在src/main/resources 目录下新增spring-mybatis.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"
           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">
    
        <!-- 导入资源文件 -->
        <context:property-placeholder location="classpath:jdbc.properties"/>
         <!-- 扫描Impl包 -->
        <context:component-scan base-package="com.sc.impl" />
    
         <!-- 配置 spring 数据源 -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="username" value="${user}"></property>
            <property name="password" value="${password}"></property>
            <property name="url" value="${jdbcUrl}"></property>
            <property name="driverClassName" value="${driverClass}"></property>
        </bean>
        <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <!-- 自动扫描mapping.xml文件 -->
            <property name="mapperLocations" value="classpath*:com/sc/mapping/*.xml"></property>
        </bean>
    
        <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.sc.dao" />
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        </bean>
    </beans>
    

    5、因为MyBatis的xml映射文件和propertis文件都在src的下级目录下,所以需要在pom.xml的build节点下加入

     <resources>
          <!-- 编译之后包含xml -->
          <resource>
            <directory>src/main/java</directory>
            <includes>
              <include>**/*.xml</include>
            </includes>
          </resource>
          <!-- 编译之后包含xml和properties -->
          <resource>
            <directory>src/main/resources</directory>
            <includes>
              <include>**/*</include>
            </includes>
          </resource>
        </resources>
    

    6、创建service层
    首先,新增接口UserServiceI

    package com.sc.service;
    
    import com.sc.pojo.User;
    
    public interface UserServiceI {
    
        /**
         * 添加用户
         * @param user
         */
        void addUser(User user);
    
        /**
         * 根据用户id获取用户
         * @param userId
         * @return
         */
        User getUserById(Integer userId);
    }
    

    其次,新增实现类UserServiceImpl

    package com.sc.impl;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import com.sc.dao.UserMapper;
    import com.sc.pojo.User;
    import com.sc.service.UserServiceI;
    
    /**
     * @author gacl
     * 使用@Service注解将UserServiceImpl类标注为一个service
     * service的id是userService
     */
    @Service("userService")
    public class UserServiceImpl implements UserServiceI {
    
        /**
         * 使用@Autowired注解标注userMapper变量,
         * 当需要使用UserMapper时,Spring就会自动注入UserMapper
         */
        @Autowired
        private UserMapper userMapper;//注入dao
    
        @Override
        public void addUser(User user) {
            userMapper.insert(user);
        }
    
        @Override
        public User getUserById(Integer userId) {
            return userMapper.selectByPrimaryKey(userId);
        }
    }
    

    7、新增测试类,结合junit

    package com.sc.test;
    
    import com.sc.pojo.User;
    import com.sc.service.UserServiceI;
    import org.junit.Before;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MyBatisTest {
    
        private UserServiceI userService;
    
        /**
         * 这个before方法在所有的测试方法之前执行,并且只执行一次
         * 所有做Junit单元测试时一些初始化工作可以在这个方法里面进行
         * 比如在before方法里面初始化ApplicationContext和userService
         */
        @Before
        public void before(){
            //使用"spring.xml"和"spring-mybatis.xml"这两个配置文件创建Spring上下文
            ApplicationContext ac = new ClassPathXmlApplicationContext("spring-mybatis.xml");
            //从Spring容器中根据bean的id取出我们要使用的userService对象
            userService = (UserServiceI) ac.getBean("userService");
        }
    
        @Test
        public void testAddUser(){
            User user = new User();
            user.setUsername("123aaaaa");
            user.setPasswd("aaaaa");
            user.setAddress("龙田");
            user.setEmail("sss");
            user.setType(1);
            userService.addUser(user);
            User user1 = userService.getUserById(1);
            System.out.println(user1);
        }
    }
    

    执行结果:


    image.png

    8、SpringMVC集成MyBatis获取信息返回到jsp页面
    添加Controller组件相关类:

    package com.sc.controller;
    
    import com.sc.impl.UserServiceImpl;
    import com.sc.pojo.User;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    
    @Controller
    @RequestMapping(value = "/user")
    public class UserController {
        @Resource
        UserServiceImpl userService;
    
        @RequestMapping(value = "/showUser")
        public String getUser(HttpServletRequest request, Model model){
    
            String  userId =  request.getParameter("id");
    
            if(!userId.equals("")&&userId!=null){
                System.out.println(userId+"-----------");
                User user = userService.getUserById(Integer.parseInt(userId));
                model.addAttribute("user",user);
            }
            return "showUser";
        }
    }
    

    在web-info/config下新增配置文件 spring-mvc-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"
           xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.2.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
    
        <!-- 扫描路径 -->
        <context:component-scan base-package="com.sc.controller">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    
        <!-- 配置根视图 -->
        <mvc:view-controller path="/" view-name="index"/>
    
        <!-- 激活基于注解的配置 @RequestMapping, @ExceptionHandler,数据绑定 ,@NumberFormat ,
        @DateTimeFormat ,@Controller ,@Valid ,@RequestBody ,@ResponseBody等  -->
        <mvc:annotation-driven/>
    
        <!-- 静态资源处理, css, js, imgs -->
        <mvc:resources location="/assets/" mapping="/assets/**"></mvc:resources>
    
        <!-- 视图层配置 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/view/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    </beans>
    

    在web.xml中加载上述配置文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://java.sun.com/xml/ns/javaee"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd  "
             version="3.0">
        <display-name>Archetype Created Web Application</display-name>
      <!-- Spring和mybatis的配置文件 -->
        <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring-mybatis.xml</param-value>
        </context-param>
        <!-- 编码过滤器 -->
        <filter>
          <filter-name>encodingFilter</filter-name>
          <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
          <async-supported>true</async-supported>
          <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
          </init-param>
        </filter>
        <filter-mapping>
          <filter-name>encodingFilter</filter-name>
          <url-pattern>/*</url-pattern>
        </filter-mapping>
        <!-- Spring监听器 -->
        <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <!-- 防止Spring内存溢出监听器 -->
        <listener>
          <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
        </listener>
        <!-- Spring MVC servlet -->
        <servlet>
          <servlet-name>SpringMVC</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/spring-mvc-servlet.xml</param-value>
          </init-param>
          <load-on-startup>1</load-on-startup>
          <async-supported>true</async-supported>
        </servlet>
        <servlet-mapping>
          <servlet-name>SpringMVC</servlet-name>
          <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
          <url-pattern>/</url-pattern>
        </servlet-mapping>
        <welcome-file-list>
          <welcome-file>/index.jsp</welcome-file>
        </welcome-file-list>
        <!-- 配置SESSION超时,单位是分钟 -->
        <session-config>
          <session-timeout>15</session-timeout>
        </session-config>
    </web-app>
    

    启动tomcat,在浏览器中输入链接:http://localhost:8080/user/showUser?id=1
    测试结果如下:

    image.png

    在整个整合过程中,遇到的问题如下:
    1、org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.sc.dao.UserMapper.selectByPrimaryKey。
    具体错误信息如下:


    image.png

    解决方案:
    需要强制将xml文件打包到war中,在pom.xml文件的bulid节点下添加以下代码

    <resources>
      <!-- 编译之后包含xml -->
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
    </resources>
    

    2、Could not resolve resource location pattern [classpath:com/sc/mapping/.xml]: class path resource [com/sc/mapping/] cannot be resolved to URL because it does not exist

    image.png
    解决方案:
    在mybatis的配置文件下 扫描不到 xml文件
    在spring-mybatis.xml中扫描xml的配置如下
    需要将classpath 为 classpath
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath*:com/sc/mapping/*.xml"></property>
    </bean>
    

    3、使用generator 自动生成重复MyBatis代码
    java.lang.IllegalArgumentException: Result Maps collection already contains value for com.sc.dao.UserMapper.BaseResultMap
    多次使用generator生成mybatis代码,在生成xxxMapper.xml文件后,再生成一次,新的内容会以追加的方式加入到原来的xxxMapper.xml文件中。


    image.png

    解决方案:
    方法一:直接删除mapping目录下的**mapper.xml文件
    方法二: 在IntrospectedTableMyBatis3Impl.getGeneratedXmlFiles方法中,isMergeable值被写死为true。而MyBatisGenerator.writeGeneratedXmlFile方法中使用到该属性,结果导致每次重新生成后都是追加。
    为了不用修改源码,重新打包,造成包不一致,所以使用反射在运行时把isMergeable强制改成false,需要新增一个插件。
    新增 OverIsMergeablePlugin 类继承PluginAdapter

    package com.sc.utils;
    
    import org.mybatis.generator.api.GeneratedXmlFile;
    import org.mybatis.generator.api.IntrospectedTable;
    import org.mybatis.generator.api.PluginAdapter;
    import java.lang.reflect.Field;
    import java.util.List;
    
    public class OverIsMergeablePlugin extends PluginAdapter {
        @Override
        public boolean validate(List<String> warnings) {
            return true;
        }
    
        @Override
        public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) {
            try {
                Field field = sqlMap.getClass().getDeclaredField("isMergeable");
                field.setAccessible(true);
                field.setBoolean(sqlMap, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }
    }
    

    将上述插件注入到配置generatorConfig.xml中
    <plugin type="com.sc.utils.OverIsMergeablePlugin" />
    注意添加的位置。


    image.png

    新增mybatis自动生成代码的测试类
    注意:这里Main类引入的是 com.sun.javaws包下的,否则会空指针异常。

    package com.sc.test;
    
    import com.sun.javaws.Main;
    import org.mybatis.generator.api.MyBatisGenerator;
    import org.mybatis.generator.config.Configuration;
    import org.mybatis.generator.config.xml.ConfigurationParser;
    import org.mybatis.generator.internal.DefaultShellCallback;
    import java.util.ArrayList;
    import java.util.List;
    
    public class GeneratorTest {
        public static void main(String[] args) throws Exception {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(Main.class.getClassLoader().getResourceAsStream("generatorConfig.xml"));
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
            System.out.println("----ok----");
        }
    }
    

    运行测试类,发现mapping目录下生成的**Mapper.xml没有自动追加,而是覆盖。

    相关文章

      网友评论

      本文标题:Spring集成MyBatis进行单元测试

      本文链接:https://www.haomeiwen.com/subject/kzepqftx.html