zoukankan      html  css  js  c++  java
  • java-Web项目开发中Spring整合Junit单元测试

    做Web开发,发现通过spring进行对象管理之后,做测试变得复杂了。

    因为所有的Bean都需要在applicationContext.xml中加载好,之后再通过@Resource去取得。

    如果每次都要整个业务流做的差不多了再去测试,这样效率很低,也很麻烦。如果单独去写一个测试用类,这样太繁琐了。

    于是想起Spring有一个测试框架,能够整合JUnit进行测试!


    1. 加入依赖的jar包

    引入一个spring整合Junitjar.(工程中需要有Junit的环境)

    spring-test-3.2.0.RELEASE.jar

    2. 创建测试源目录和包

      在此,推荐创建一个和src平级的源文件目录,因为src内的类都是为日后产品准备的,而此处的类仅仅用于测试。而包的名称可以和src中的目录同名,这样由于在test源目录中,所以不会有冲突,而且名称又一模一样,更方便检索。


    3. 创建测试类

           创建一个测试用的类,推荐名称为 “被测试类名称 + Test”。

    :使用注解开发:

    @RunWith(SpringJUnit4ClassRunner.class) //固定写法

    @ContextConfiguration("classpath:applicationContext.xml")//配置文件的路径

    //测试类

    public class SpringTest1 {

    //属性对象的注入

    @Resource(name="userService")

    private UserService userService;

    //测试方法

    @Test

    public void demo1(){

    userService.save();

    }

    }


    package com.taotao.controller;

    import java.util.List;

    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import com.taotao.mapper.TbItemMapper;
    import com.taotao.pojo.TbItem;
    import com.taotao.pojo.TbItemExample;

    public class TestPageHelper {
    @Test
    public void testPageHelper() {
    ApplicationContext applicationContext = new                        ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
    //从spring容器中获得Mapper的代理对象
    TbItemMapper mapper = applicationContext.getBean(TbItemMapper.class);
    //执行查询,并分页
    TbItemExample example = new TbItemExample();
    //分页处理
    PageHelper.startPage(2, 10);
    //取商品列表
    for (TbItem tbItem : list) {
    System.out.println(tbItem.getTitle());
    }
    //取分页信息
    long total = pageInfo.getTotal();
    System.out.println("共有商品:"+ total);

    }
  • 相关阅读:
    ocilib(简介2)
    C++ Socket编程步骤 (转载)
    服务端和客户端的疑问
    var和public的区别
    vs2010如何设置能实现输入关键字的时候自动提示呢?
    ocilib(简介)
    iostream.h , iostream
    error C2110: cannot add two pointers
    Array 越界不报错的问题
    char* + int or char or ...
  • 原文地址:https://www.cnblogs.com/luckForever/p/7254101.html
Copyright © 2011-2022 走看看