【Spring】Junit加载Spring容器作单元测试

> 引入相关Jar包

一、均需引入所需的包

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.10.RELEASE</version>
</dependency>

>配置文件加载方式

(a)加载配置文件<原始的手动加载方式>

ApplicationContext context = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");
new ClassPathXmlApplicationContext("applicationContext.xml");// 从classpath中加载
new FileSystemXmlApplicationContext("classpath:地址");// 没有classpath表示当前目录

(b)注解的方式自动加载方式

 @org.springframework.test.context.ContextConfiguration(locations={"file:WebRoot/WEB-INF/applicationContext.xml"})

 @org.springframework.test.context.ContextConfiguration(locations={"classpath:applicationContext.xml"}) 
    @RunWith(SpringJUnit4ClassRunner.class)  //使用junit4进行测试
@ContextConfiguration
({"/spring/app*.xml","/spring/service/app*.xml"}) //加载配置文件 //------------如果加入以下代码,所有继承该类的测试类都会遵循该配置,也可以不加,在测试类的方法上///控制事务,参见下一个实例
//这个非常关键,如果不加入这个注解配置,事务控制就会完全失效!
//@Transactional
//这里的事务关联到配置文件中的事务控制器(transactionManager = "transactionManager"),同时//指定自动回滚(defaultRollback = true)。这样做操作的数据才不会污染数据库!
//@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
//------------
public class BaseJunit4Test {
}

>原始的用法

测试类中要设置加载哪些Spring的配置(我这里是“/config/application*.xml”),然后就可以注入容器中的bean了。这里列举用注解的方式

package com.nicchagil.mybatis3spring3intg.junit;

import java.util.List;

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 com.nicchagil.mybatis3spring3intg.bean.User;
import com.nicchagil.mybatis3spring3intg.service.UserService; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/config/application*.xml"})
public class JunitTest { @Autowired
private UserService userService; @Test
public void c1() {
List<User> userList = userService.query(new User());
System.out.println(userList);
} }

在具体的测试类中,采用手动加载配置文件的方式进行JUnit测试,有如下缺点

1)导致多次Spring容器初始化问题

2)需要使用硬编码方式手工获取Bean ,需要强制转换

3)数据库现场容易遭受破坏(理想的状态:自动回滚对数据库的操作,保证数据库的现场不被破坏,因此重复测试不会发生问题)

4)不方便对数据操作正确性进行检查(理想状态:过jdbcTemplate在同一事务中访问数据库,查询数据的变化,验证操作的正确性)

> 常见的用法

常用的方式是将加载配置的部分公用出来:

package com.nicchagil.mybatis3spring3intg.junit;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/config/application*.xml"})
public class BaseJunit { }

然后需要的各个测试类继承公用类:

package com.nicchagil.mybatis3spring3intg.junit;

import java.util.List;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import com.nicchagil.mybatis3spring3intg.bean.User;
import com.nicchagil.mybatis3spring3intg.service.UserService; public class UserServiceTest extends BaseJunit { @Autowired
private UserService userService;
  @Resource //自动注入,默认按名称  
  private IBaseDao baseDao;   @Test //标明是测试方法
  @Transactional //标明此方法需使用事务
  @Rollback(false) //标明使用完此方法后事务不回滚,true时为回滚
  public void c1() {
    List<User> userList = userService.query(new User());
    System.out.println(userList);
  }
}
//复习:@Autowired & @Resource 的区别
//@Autowired注解是按类型装配依赖对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它required属性为false。如果我们想使用按名称装配,可以结合@Qualifier注解一起使用。如下:
// @Autowired @Qualifier("personDaoBean")
// private PersonDao personDao; //@Resource注解和@Autowired一样,也可以标注在字段或属性的setter方法上,但它默认按名称装配。名称可以通过@Resource的name属性指定,如果没有指定name属性,当注解标注在字段上,即默认取字段的名称作为bean名称寻找依赖对象,当注解标注在属性的setter方法上,即默认取属性名作为bean名称寻找依赖对象。
// @Resource(name=“personDaoBean”)
// private PersonDao personDao;//用于字段上 //注意:如果没有指定name属性,并且按照默认的名称仍然找不到依赖对象时, @Resource注解会回退到按类型装配。但一旦指定了name属性,就只能按名称装配了。

 

【Spring】Junit加载Spring容器作单元测试(整理)的更多相关文章

  1. 【Spring】Junit加载Spring容器作单元测试

    如果我们需要对我们的Service方法作单元测试,恰好又是用Spring作为IOC容器的,我们可以这么配置Junit加载Spring容器,方便做单元测试. > 基本的搭建 (1)引入所需的包 & ...

  2. Junit加载Spring容器作单元测试

    阅读目录 > 基本的搭建 > 常见的用法 如果我们需要对我们的Service方法作单元测试,恰好又是用Spring作为IOC容器的,我们可以这么配置Junit加载Spring容器,方便做单 ...

  3. spring boot 加载web容器tomcat流程源码分析

    spring boot 加载web容器tomcat流程源码分析 我本地的springboot版本是2.5.1,后面的分析都是基于这个版本 <parent> <groupId>o ...

  4. junit测试用例加载spring配置文件

    junit加载pom引用项目的xml配置文件,如果定义了<beans profile="dev">,必须在测试用例类上面加上标记 @ActiveProfiles(&qu ...

  5. 加载spring容器

    import org.springframework.context.ApplicationContext; import org.springframework.context.support.Cl ...

  6. Spring Boot中采用Mockito来mock所测试的类的依赖(避免加载spring bean,避免启动服务器)

    最近试用了一下Mockito,感觉真的挺方便的.举几个应用实例: 1,需要测试的service中注入的有一个dao,而我并不需要去测试这个dao的逻辑,只需要对service进行测试.这个时候怎么办呢 ...

  7. Spring中加载xml配置文件的六种方式

    Spring中加载xml配置文件的六种方式 博客分类: Spring&EJB XMLSpringWebBeanBlog  因为目前正在从事一个项目,项目中一个需求就是所有的功能都是插件的形式装 ...

  8. Spring中加载配置文件的方式

    原文:http://blog.csdn.net/snowjlz/article/details/8158560 Spring 中加载XML配置文件的方式,好像有3种, XML是最常见的Spring 应 ...

  9. Web.xml配置详解之context-param (加载spring的xml,然后初始化bean看的)

    http://www.cnblogs.com/goody9807/p/4227296.html(很不错啊) 容器先加载spring的xml,然后初始化bean时,会为bean赋值,包括里面的占位符

随机推荐

  1. Qt debug和release

    debug会默认给变量赋初始值,但是release不会. 所以: 在头文件中声明指针P* p时,最好给它初始化:P* p=NULL; 不然有可能造成野指针的情况

  2. JUnit4 入门笔记

    Test注解的两个可选参数 expected timeout The Test annotation supports two optional parameters. The first, expe ...

  3. springboot学习(三)——使用HttpMessageConverter进行http序列化和反序列化

    以下内容,如有问题,烦请指出,谢谢! 对象的序列化/反序列化大家应该都比较熟悉:序列化就是将object转化为可以传输的二进制,反序列化就是将二进制转化为程序内部的对象.序列化/反序列化主要体现在程序 ...

  4. window下安裝redis服務

    一.下载windows版本的Redis github下载地址:https://github.com/MicrosoftArchive/redis/releases/tag/win-3.2.100   ...

  5. 有意思的随机数 Random

    今天看到stackoverflow上一篇关于随机数的提问,关于如何用随机数生成 "hello world"的有趣问题 : 大家都知道JDK里面的Random类生成随机数其实并不是真 ...

  6. NumPy统计函数

    NumPy - 统计函数 NumPy 有很多有用的统计函数,用于从数组中给定的元素中查找最小,最大,百分标准差和方差等. 函数说明如下: numpy.amin() 和 numpy.amax() 这些函 ...

  7. Linux find 命令大全

    find 含义: 顾名思义,是从来查找满足条件的内容. 从指定目录,递归的查找满足条件的内容. 格式: find [查询目录] [参数] [匹配方式] 文件操作: -name : 查找文件名  ( f ...

  8. iOS-免证书真机调试

     使用方法: 1.新建一个普通的项目 2.进入xcode,菜单栏选择xcode –> preferences (快捷键 command + ,) 3.在Accounts选项卡添加自己的Apple ...

  9. NPOI将xls文件解析为DataTable类数据

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.I ...

  10. Java8_00_资源帖

    一.官方资料 Java Platform Standard Edition 8 Documentation The Java™ Tutorials Java 8 API 二.精选资料 三.参考资料