Spring 单元测试

Spring 单元测试

项目 gitee 地址

0. 导入junit 依赖

    <!-- 测试     -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

1. 配置文件

  1. Spring 配置文件

    • Spring-dao.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"
             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">
      
       <!-- 配置整合mybatis -->
          <!-- 1.关联数据库文件 -->
          <context:property-placeholder location="classpath:database.properties"/>
      
          <!-- 2.数据库连接池 -->
          <!--数据库连接池
              dbcp 半自动化操作 不能自动连接
              c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
          -->
          <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
              <!-- 配置连接池属性 -->
              <property name="driverClass" value="${jdbc.driver}"/>
              <property name="jdbcUrl" value="${jdbc.url}"/>
              <property name="user" value="${jdbc.username}"/>
              <property name="password" value="${jdbc.password}"/>
      
              <!-- c3p0连接池的私有属性 -->
              <property name="maxPoolSize" value="30"/>
              <property name="minPoolSize" value="10"/>
              <!-- 关闭连接后不自动commit -->
              <property name="autoCommitOnClose" value="false"/>
              <!-- 获取连接超时时间 -->
              <property name="checkoutTimeout" value="10000"/>
              <!-- 当获取连接失败重试次数 -->
              <property name="acquireRetryAttempts" value="2"/>
          </bean>
      
          <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
              <!-- 注入数据库连接池 -->
              <property name="dataSource" ref="dataSource"/>
              <!-- 配置 MyBaties 全局配置文件:mybatis-config.xml -->
              <property name="configLocation" value="classpath:mybatis-config.xml"/>
          </bean>
      
      
          <!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
          <!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
          <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
              <!-- 注入sqlSessionFactory -->
              <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
              <!-- 给出需要扫描Dao接口包 -->
              <property name="basePackage" value="com.zhiyou100.mapper"/>
          </bean>
      
      
      </beans>
      
    • spring-mvc.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.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd">
      
          <!-- 配置SpringMVC -->
          <!-- 1.开启SpringMVC注解驱动 -->
          <mvc:annotation-driven/>
          <!-- 2.静态资源默认servlet配置-->
          <mvc:default-servlet-handler/>
      
          <!-- 3.配置jsp 显示ViewResolver视图解析器 -->
          <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
              <property name="prefix" value="/"/>
              <property name="suffix" value=".jsp"/>
          </bean>
      
          <!-- 4.扫描web相关的bean -->
          <context:component-scan base-package="com.zhiyou100.action"/>
      
          <!-- 5 配置多部件表单的解析器 -->
          <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
              <!--上传文件的最大大小,单位为字节 -->
              <property name="maxUploadSize" value="17367648787"/>
              <!-- 上传文件的编码 -->
              <property name="defaultEncoding" value="UTF-8"/>
          </bean>
      
          <!-- 6 拦截器 配置   -->
          <mvc:interceptors>
              <mvc:interceptor>
                  <!--/** 包括路径及其子路径-->
                  <!--/admin/* 拦截的是/admin/add等等这种 , /admin/add/user不会被拦截-->
                  <!--/admin/** 拦截的是/admin/下的所有-->
                  <mvc:mapping path="/**"/>
                  <bean id="loginInterceptor" class="com.zhiyou100.interceptor.MyInterceptor"/>
              </mvc:interceptor>
          </mvc:interceptors>
      
      
      </beans>
      
    • spring-service.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"
             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">
      
          <!-- 扫描service相关的bean -->
          <context:component-scan base-package="com.zhiyou100"/>
      
      
          <!-- 配置事务管理器 -->
          <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
              <!-- 注入数据库连接池 -->
              <property name="dataSource" ref="dataSource"/>
          </bean>
      
      </beans>
      

  1. mybatis 配置文件
  • database.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.217.82:3306/db_zygy
jdbc.username=root
jdbc.password=1
  • mybatis-config.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    
    <configuration>
    
        <settings>
            <setting name="logImpl" value="STDOUT_LOGGING"/>
            <!-- 显示sql语句 -->
            <setting name="mapUnderscoreToCamelCase" value="true"/>
            <!-- 命名转换 -->
        </settings>
    
        <typeAliases>
            <package name="com.zhiyou100.entity"/>
            <!--给实体类起别名 -->
        </typeAliases>
    
        <plugins>
            <!-- com.github.pagehelper为PageHelper类所在包名 -->
            <plugin interceptor="com.github.pagehelper.PageInterceptor">
                <!-- pageNum<=0 时会查询第一页   reasonable=true -->
                <!-- 指定数据库方言   helperDialect=mysql -->
                <property name="params" value="reasonable=true;helperDialect=mysql"/>
            </plugin>
        </plugins>
        <mappers>
            <package name="com.zhiyou100.mapper"/>
            <!-- 引入所有的sql映射文件 -->
        </mappers>
    
    </configuration>
    
  1. Spring 综合配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <import resource="classpath:spring/spring-dao.xml"/>
        <import resource="classpath:spring/spring-service.xml"/>
        <import resource="classpath:spring/spring-mvc.xml"/>
    
    </beans>
    
  2. web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
    
        <!--DispatcherServlet-->
        <servlet>
            <servlet-name>DispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <!--一定要注意:我们这里加载的是总的配置文件,之前被这里坑了!-->
                <param-value>classpath:applicationContext.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>DispatcherServlet</servlet-name>
            <url-pattern>*.action</url-pattern>
        </servlet-mapping>
    
        <!--encodingFilter-->
        <filter>
            <filter-name>encodingFilter</filter-name>
            <filter-class>
                org.springframework.web.filter.CharacterEncodingFilter
            </filter-class>
            <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>
    
        <!--Session过期时间-->
    <!--    <session-config>-->
    <!--        <session-timeout>30</session-timeout>-->
    <!--    </session-config>-->
    
        <!-- 自定义编码集 过滤器   -->
        <filter>
            <filter-name>GenericEncodingFilter</filter-name>
            <filter-class>com.zhiyou100.filter.GenericEncodingFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>GenericEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
        <!-- 指定初始化参数 记录文件的路径 -->
        <context-param>
            <param-name>path</param-name>
            <param-value>/Users/yang/Desktop/java26/zygy</param-value>
        </context-param>
        <context-param>
            <param-name>key</param-name>
            <param-value>a1b2</param-value>
        </context-param>
    
    
    </web-app>
    
  3. pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.zhiyou100</groupId>
        <artifactId>ApartmentInformationManagementSystem</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <!-- 强制排出文件  -->
        <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
            </resources>
        </build>
    
        <!--  控制 版本    -->
        <properties>
    
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <!--  编译jdk版本  -->
            <jdk.version>1.8</jdk.version>
    
            <!--  依赖版本  -->
            <!--  spring 版本      -->
            <spring.version>4.1.2.RELEASE</spring.version>
            <!--  sql 版本      -->
            <mysql.version>8.0.20</mysql.version>
    
    
        </properties>
    
        <!-- 导入依赖   -->
        <dependencies>
            <!-- spring start -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-oxm</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
            </dependency>
            <!-- spring end -->
    
            <!-- 其他开始-->
            <dependency>
                <!--  lombok 依赖 偷懒神器 @Data 自动生成 get set toString 无参构造方法 equals hashCode -->
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.16.20</version>
                <scope>provided</scope>
            </dependency>
    
            <dependency>
                <!--  c3po 依赖              -->
                <groupId>c3p0</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.1.2</version>
            </dependency>
    
    
            <!--  hutool 工具类      -->
            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>4.5.15</version>
            </dependency>
    
    
            <dependency>
                <!-- fastJson  -->
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.68</version>
            </dependency>
    
    
            <dependency>
                <!--  MySQL  驱动         -->
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
    
            <dependency>
                <!-- dom 解析           -->
                <groupId>dom4j</groupId>
                <artifactId>dom4j</artifactId>
                <version>1.6.1</version>
            </dependency>
    
            <!-- web 开始  -->
    <!--        <dependency>-->
    <!--            <groupId>javax</groupId>-->
    <!--            <artifactId>javaee-api</artifactId>-->
    <!--            <version>6.0</version>-->
    <!--            <scope>provided</scope>-->
    <!--        </dependency>-->
    
            <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.1.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>javax.ws.rs</groupId>
                <artifactId>javax.ws.rs-api</artifactId>
                <version>2.0</version>
            </dependency>
            <dependency>
                <groupId>javax.websocket</groupId>
                <artifactId>javax.websocket-api</artifactId>
                <version>1.0</version>
            </dependency>
            <dependency>
                <groupId>javax.annotation</groupId>
                <artifactId>javax.annotation-api</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>javax.transaction</groupId>
                <artifactId>javax.transaction-api</artifactId>
                <version>1.2</version>
            </dependency>
            <!-- web 结束  -->
    
    
            <dependency>
                <!--  cglib  依赖        -->
                <groupId>cglib</groupId>
                <artifactId>cglib</artifactId>
                <version>2.2.2</version>
            </dependency>
    
    
            <!--   mybatis 依赖      -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.5</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.2</version>
            </dependency>
            <!-- 分页 -->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>5.1.10</version>
            </dependency>
    
    
            <!-- 测试     -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
    
    
            <dependency>
                <!--  commons-io         -->
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.2</version>
            </dependency>
    
    
            <dependency>
                <!--  文件上传  -->
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.1</version>
            </dependency>
    
    
            <!-- 其他结束-->
        </dependencies>
    
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-framework-bom</artifactId>
                    <version>${spring.version}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    </project>
    

2. 测试 mapper

  • LesseeMapper.java

    package com.zhiyou100.mapper;
    
    import com.zhiyou100.entity.Lessee;
    
    import java.util.List;
    
    /**
     * 组合信息 mapper
     *
     * @author yang
     */
    public interface LesseeMapper {
        /**
         * 获取所有的租户信息表(Lessee)
         *
         * @return 所有的租户信息表(Lessee)
         */
        List<Lessee> listLessees();
    
        /**
         * 根据 lid 获取一个 租户信息表
         *
         * @param lid 唯一的 id
         * @return 根据 id 查找的 租户信息表
         */
        Lessee selectOneByLid(Integer lid);
    
        /**
         * 根据 传入的 Lessee 更新一个
         *
         * @param lessee 参数 Lessee
         */
        void updateOneLessee(Lessee lessee);
    
        /**
         * 根据 cid 删除一个
         *
         * @param cid 要删除租户信息表的 cid
         */
        void deleteOneByCid(Integer cid);
    
        /**
         * 添加一个合同
         *
         * @param lessee 要添加的租户信息表
         */
        void insertOne(Lessee lessee);
    }
    
  • LesseeMapperTest.java

    package com.zhiyou100.mapper;
    
    import com.zhiyou100.entity.Lessee;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import javax.transaction.Transactional;
    import java.util.Date;
    
    /**
     * spring dao 测试
     * // @RunWith(SpringJUnit4ClassRunner.class) 必须
     * // @ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:mybatis-config.xml"}) 加载配置文件
     * // @Transactional 单元测试执行完后会撤销对数据库的修改
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:mybatis-config.xml"})
    @Transactional
    public class LesseeMapperTest {
    
        @Autowired
        private LesseeMapper lesseeMapper;
    
    
        @Test
        public void listLessees() {
            lesseeMapper.listLessees().forEach(System.out::println);
        }
    
        @Test
        public void selectOneByLid() {
            System.out.println(lesseeMapper.selectOneByLid(1));
        }
    
        @Test
        public void updateOneLessee() {
            final Lessee wang = Lessee.builder()
                    .lid(1)
                    .lname("王渊")
                    .ltel("110")
                    .lsex("男")
                    .lnativeplace("郑州")
                    .lidcard("411323")
                    .laddtime(new Date())
                    .build();
    
    
            lesseeMapper.updateOneLessee(wang);
    
            System.out.println(lesseeMapper.selectOneByLid(1));
        }
    
        @Test
        public void deleteOneByCid() {
            lesseeMapper.deleteOneByCid(1);
            System.out.println(lesseeMapper.selectOneByLid(1));
        }
    
        @Test
        public void insertOne() {
            final Lessee wang = Lessee.builder()
                    .lname("王渊")
                    .ltel("110")
                    .lsex("男")
                    .lnativeplace("郑州")
                    .lidcard("411323")
                    .laddtime(new Date())
                    .build();
    
            lesseeMapper.insertOne(wang);
    
            //for (Lessee listLessee : lesseeMapper.listLessees()) {
            //    System.err.println(listLessee);
            //}
        }
    
        @Test
        public void insertList(){
            int max=100;
            for (int i = 0; i < max; i++) {
                insertOne();
            }
        }
    }
    

3. 测试 service

  • LesseeService.java

    package com.zhiyou100.service;
    
    import com.zhiyou100.entity.Lessee;
    
    import java.util.List;
    
    /**
     * 租客信息表
     *
     * @author yang
     * @version 1.0.0
     * @date 2020-08-31 10:22
     */
    public interface LesseeService {
        /**
         * 获取所有的租户信息表(Lessee)
         *
         * @return 所有的租户信息表(Lessee)
         */
        List<Lessee> listLessees();
    
        /**
         * 根据 lid 获取一个 租户信息表
         *
         * @param lid 唯一的 id
         * @return 根据 id 查找的 租户信息表
         */
        Lessee selectOneByLid(Integer lid);
    
        /**
         * 根据 传入的 Lessee 更新一个
         *
         * @param lessee 参数 Lessee
         */
        void updateOneLessee(Lessee lessee);
    
        /**
         * 根据 cid 删除一个
         *
         * @param cid 要删除租户信息表的 cid
         */
        void deleteOneByCid(Integer cid);
    
        /**
         * 添加一个合同
         *
         * @param lessee 要添加的租户信息表
         */
        void insertOne(Lessee lessee);
    }
    
    
  • LesseeServiceTest.java

    package com.zhiyou100.service;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import javax.transaction.Transactional;
    
    /**
     * service 层测试
     * // @RunWith(SpringJUnit4ClassRunner.class) 必须
     * * // @ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:mybatis-config.xml"}) 加载配置文件
     * * // @Transactional 单元测试执行完后会撤销对数据库的修改
     */
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:mybatis-config.xml"})
    @Transactional
    public class LesseeServiceTest {
    
        @Autowired
        private LesseeService lesseeService;
        @Test
        public void listLessees() {
            lesseeService.listLessees().forEach(System.err::println);
        }
    
        @Test
        public void selectOneByLid() {
        }
    
        @Test
        public void updateOneLessee() {
        }
    
        @Test
        public void deleteOneByCid() {
        }
    
        @Test
        public void insertOne() {
        }
    }
    

4. 测试 action

  • LesseeAction.java

    package com.zhiyou100.action;
    
    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import com.zhiyou100.entity.Lessee;
    import com.zhiyou100.service.LesseeService;
    import com.zhiyou100.util.object.ObjectUtil;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.propertyeditors.CustomDateEditor;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.ServletRequestDataBinder;
    import org.springframework.web.bind.annotation.InitBinder;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.UnsupportedEncodingException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    
    /**
     * 租客信息 action
     *
     * @author yang
     * @version 1.0.0
     * @date 2020-08-31 11:11
     */
    @Controller
    @RequestMapping("/lessee")
    public class LesseeAction {
        @Autowired
        private LesseeService lesseeService;
    
        @RequestMapping("/list.action")
        public String listHouses(Model model,
                                 @RequestParam(defaultValue = "1",  value = "pageNo") Integer pageNo
        ) {
            // 每页显示的记录数
            int pageSize = 10;
    
            // 分页查询
            PageHelper.startPage(pageNo, pageSize);
    
            // 获取所有的信息
            final List<Lessee> list = lesseeService.listLessees();
    
            // 使用 PageInfo<Lessee> 结果进行封装
    
            final PageInfo<Lessee> pageInfo = new PageInfo<>(list);
    
            model.addAttribute("pageInfoLessee", pageInfo);
    
            return "view/lessee/list";
        }
    
        @RequestMapping("/getOneById.action")
        public String getOneByHid(Integer lid, String method, Model model) {
            final Lessee lessee = lesseeService.selectOneByLid(lid);
            if (lessee != null) {
                // 有,放入区域中,跳转 到 详情页面
                if (method == null || method.trim().length() == 0) {
                    // 跳转到 view/lessee/detail
                    model.addAttribute("lessee", lessee);
                    return "view/lessee/detail";
                } else {
                    // 跳转到更新界面
                    model.addAttribute("lessee", lessee);
                    return "view/lessee/update";
                }
    
            } else {
                // 没有,返回列表
                return "view/lessee/list";
            }
        }
    
        @RequestMapping("/insertOne.action")
        public String insertOne(Lessee lessee, HttpServletRequest request) {
    
            String id = "lid";
            String addTime = "laddtime";
            if (ObjectUtil.onlyOneFiledIsNullAndTheFiledIsId(lessee, id, addTime)) {
                // lid 和  laddtime 字段为空,合法
                // 设置时间
                lessee.setLaddtime(new Date());
                lesseeService.insertOne(lessee);
            }
    
            return "/view/lessee/list";
        }
    
        @RequestMapping("/updateOne.action")
        public String updateOneByCid(Lessee lessee) {
    
            String addTime = "laddtime";
            if (ObjectUtil.onlyOneFiledIsNullAndTheFiledIsId(lessee, addTime)) {
                // laddtime 字段为空,合法,设置添加时间
                lessee.setLaddtime(new Date());
                lesseeService.updateOneLessee(lessee);
            }
    
            return "/view/lessee/list";
        }
    
        /**
         * 自定义一个 日期属性编辑器
         * yyyy-MM-dd'T'HH:mm:ss 针对 <input type="datetime-local" value="2020-08-28T20:49:16">
         *
         * @param request HttpServletRequest
         * @param binder  binder
         */
        @InitBinder
        public void myDateBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws UnsupportedEncodingException {
            request.setCharacterEncoding("utf-8");
            final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
            binder.registerCustomEditor(Date.class, new CustomDateEditor(simpleDateFormat, true));
        }
    
        @RequestMapping("/deleteOneById.action")
        public String deleteOneByHid(Integer lid) {
            if (lid != null) {
                lesseeService.deleteOneByCid(lid);
            }
            return "view/lessee/list";
        }
    
    }
    
    
  • LesseeActionTest.java

    package com.zhiyou100.action;
    
    import com.zhiyou100.entity.Lessee;
    import com.zhiyou100.service.LesseeService;
    import lombok.SneakyThrows;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.MvcResult;
    import org.springframework.test.web.servlet.ResultActions;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    
    import javax.transaction.Transactional;
    import java.util.Date;
    
    /**
     * Controller 测试类
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:mybatis-config.xml"})
    @Transactional
    public class LesseeActionTest {
    
        @Autowired
        private LesseeAction lesseeAction;
    
        @Autowired
        private LesseeService lesseeService;
    
        private MockMvc mockMvc;
    
        @Before
        public void setup() {
            mockMvc = MockMvcBuilders.standaloneSetup(lesseeAction).build();
        }
    
        @SneakyThrows
        @Test
        public void listHouses() {
            final ResultActions resultActions = this.mockMvc.perform(
                    MockMvcRequestBuilders
                            .post("/lessee/list.action")
                            .param("pageNo", "5")
            );
    
            final MvcResult mvcResult = resultActions.andReturn();
    
            // 取出来 request 中的属性
            System.out.println(mvcResult.getRequest().getAttribute("pageInfoLessee"));
    
            //  从 response 中取出 状态码
            System.out.println("状态码 " + mvcResult.getResponse().getStatus());
    
        }
    
        @SneakyThrows
        @Test
        public void getOneByHid() {
            final ResultActions resultActions = this.mockMvc.perform(
                    MockMvcRequestBuilders
                            .post("/lessee/getOneById.action")
                            .param("lid", "1")
                            .param("method", "a")
            );
    
            // 获取 结果集
            final MvcResult mvcResult = resultActions.andReturn();
    
            // 取出来 request 中的属性
            System.out.println(mvcResult.getRequest().getAttribute("lessee"));
    
            //  从 response 中取出 状态码
            System.out.println("状态码 " + mvcResult.getResponse().getStatus());
    
            System.out.println(mvcResult.getModelAndView().getViewName());
        }
    
        @Test
        public void insertOne() throws Exception {
    
            final Lessee wang = Lessee.builder()
                    //.lid(1)
                    .lname("杨磊")
                    .ltel("100")
                    .lsex("男")
                    .lnativeplace("南阳")
                    .lidcard("411323")
                    .laddtime(new Date())
                    .build();
    
            final ResultActions resultActions = this.mockMvc.perform(
                    MockMvcRequestBuilders
                            .post("/lessee/insertOne.action")
                            .param("lid", "1")
                            .param("lname", wang.getLname())
                            .param("ltel", wang.getLtel())
                            .param("lsex", wang.getLsex())
                            .param("lnativeplace", wang.getLnativeplace())
                            .param("lidcard", wang.getLidcard())
                    //.param("laddtime",wang.getLaddtime())
    
    
            );
    
            // 获取 结果集
            final MvcResult mvcResult = resultActions.andReturn();
    
            //  从 response 中取出 状态码
            System.out.println("状态码 " + mvcResult.getResponse().getStatus());
    
            // 获取 视图名字
            System.out.println(mvcResult.getModelAndView().getViewName());
    
            // 只要 name 等于 杨磊的
            lesseeService.listLessees().stream().filter(lessee ->
                    lessee.getLname().equalsIgnoreCase("杨磊")
            ).forEach(System.out::println);
        }
    
        @Test
        public void updateOneByCid() throws Exception {
            System.out.println(System.currentTimeMillis());
            final Lessee wang = Lessee.builder()
                    .lid(1)
                    .lname("杨磊")
                    .ltel("100")
                    .lsex("男")
                    .lnativeplace("南阳")
                    .lidcard("411323")
                    .laddtime(new Date())
                    .build();
    
            final ResultActions resultActions = this.mockMvc.perform(
                    MockMvcRequestBuilders
                            .post("/lessee/updateOne.action")
                            //.param("lid","1")
                            .param("lname", wang.getLname())
                            .param("ltel", wang.getLtel())
                            .param("lsex", wang.getLsex())
                            .param("lnativeplace", wang.getLnativeplace())
                            .param("lidcard", wang.getLidcard())
                    //.param("laddtime",wang.getLaddtime())
    
    
            );
    
            // 获取 结果集
            final MvcResult mvcResult = resultActions.andReturn();
    
            //  从 response 中取出 状态码
            System.out.println("状态码 " + mvcResult.getResponse().getStatus());
    
            // 获取 视图名字
            System.out.println(mvcResult.getModelAndView().getViewName());
    
            // 只要 name 等于 杨磊的
            //lesseeService.listLessees().stream().filter(lessee ->
            //        lessee.getLname().equalsIgnoreCase("杨磊")
            //).forEach(System.out::println);
            System.err.println(lesseeService.selectOneByLid(1));
    
            System.out.println(System.currentTimeMillis());
    
        }
    
        @Test
        public void myDateBinder() throws Exception {
        }
    
        @Test
        public void deleteOneByHid() throws Exception {
            System.err.println(lesseeService.selectOneByLid(1));
    
            final ResultActions resultActions = this.mockMvc.perform(
                    MockMvcRequestBuilders
                            .post("/lessee/deleteOneById.action")
                    //.param("lid","")
            );
    
            // 获取 结果集
            final MvcResult mvcResult = resultActions.andReturn();
    
            //  从 response 中取出 状态码
            System.out.println("状态码 " + mvcResult.getResponse().getStatus());
    
            // 获取 视图名字
            System.out.println(mvcResult.getModelAndView().getViewName());
            System.err.println(lesseeService.selectOneByLid(1));
        }
    }
    
posted @ 2020-09-03 11:47  javaYanglei  阅读(380)  评论(0编辑  收藏  举报