JUnit

Stella981
• 阅读 748

一、会用Spring测试套件的好处

在开发基于Spring的应用时,如果你还直接使用Junit进行单元测试,那你就错过了Spring为我们所提供的饕餮大餐了。使用Junit直接进行单元测试有以下四大不足:

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

根据JUnit测试方法的调用流程,每执行一个测试方法都会创建一个测试用例的实例并调用setUp()方法。由于一般情况下,我们在setUp()方法中初始化Spring容器,这意味着如果测试用例有多少个测试方法,Spring容器就会被重复初始化多次。虽然初始化Spring容器的速度并不会太慢,但由于可能会在Spring容器初始化时执行加载Hibernate映射文件等耗时的操作,如果每执行一个测试方法都必须重复初始化Spring容器,则对测试性能的影响是不容忽视的;

使用Spring测试套件,Spring容器只会初始化一次

2)需要使用硬编码方式手工获取Bean

在测试用例类中我们需要通过ctx.getBean()方法从Spirng容器中获取需要测试的目标Bean,并且还要进行强制类型转换的造型操作。这种乏味的操作迷漫在测试用例的代码中,让人觉得烦琐不堪;

使用Spring测试套件,测试用例类中的属性会被自动填充Spring容器的对应Bean,无须在手工设置Bean!

3)数据库现场容易遭受破坏

测试方法对数据库的更改操作会持久化到数据库中。虽然是针对开发数据库进行操作,但如果数据操作的影响是持久的,可能会影响到后面的测试行为。举个例子,用户在测试方法中插入一条ID为1的User记录,第一次运行不会有问题,第二次运行时,就会因为主键冲突而导致测试用例失败。所以应该既能够完成功能逻辑检查,又能够在测试完成后恢复现场,不会留下“后遗症”;

使用Spring测试套件,Spring会在你验证后,自动回滚对数据库的操作,保证数据库的现场不被破坏,因此重复测试不会发生问题!

4)不方便对数据操作正确性进行检查

假如我们向登录日志表插入了一条成功登录日志,可是我们却没有对t_login_log表中是否确实添加了一条记录进行检查。一般情况下,我们可能是打开数据库,肉眼观察是否插入了相应的记录,但这严重违背了自动测试的原则。试想在测试包括成千上万个数据操作行为的程序时,如何用肉眼进行检查?

只要你继承Spring的测试套件的用例类,你就可以通过jdbcTemplate(或Dao等)在同一事务中访问数据库,查询数据的变化,验证操作的正确性!

Spring提供了一套扩展于Junit测试用例的测试套件,使用这套测试套件完全解决了以上四个问题,让我们测试Spring的应用更加方便。这个测试套件主要由org.springframework.test包下的若干类组成,使用简单快捷,方便上手。

二、使用方法

1)基本用法

package com.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:config/applicationContext-*.xml", "classpath:services/ext/service-*.xml" })
public class UserServiceTest {

    @Resource
    private IUserService userService;

    @Test
    public void testAddOpinion1() {
        userService.downloadCount(1);
        System.out.println(1);
    }

    @Test
    public void testAddOpinion2() {
        userService.downloadCount(2);
        System.out.println(2);
    }
}

@RunWith(SpringJUnit4ClassRunner.class) 用于配置spring中测试的环境

@ContextConfiguration(locations = { "classpath:config/applicationContext-*.xml", "classpath:services/ext/service-*.xml" })用于指定配置文件所在的位置

@Resource注入Spring容器Bean对象,注意与@Autowired区别

2)事务用法

package com.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:config/applicationContext-*.xml", "classpath:services/ext/service-*.xml" })
@Transactional
@TransactionConfiguration(transactionManager = "transactionManager")
//@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class UserServiceTest {

    @Resource
    private IUserService userService;

    @Test
//    @Transactional
    public void testAddOpinion1() {
        userService.downloadCount(1);
        System.out.println(1);
    }

    @Test
    @Rollback(false)
    public void testAddOpinion2() {
        userService.downloadCount(2);
        System.out.println(2);
    }
}

@TransactionConfiguration(transactionManager="transactionManager")读取Spring配置文件中名为transactionManager的事务配置,defaultRollback为事务回滚默认设置。该注解是可选的,可使用@Transactional与@Rollback配合完成事务管理。当然也可以使用@Transactional与@TransactionConfiguration配合。

@Transactional开启事务。可放到类或方法上,类上作用于所有方法。

@Rollback事务回滚配置。只能放到方法上。

3)继承AbstractTransactionalJUnit4SpringContextTests

package com.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;

@ContextConfiguration(locations = { "classpath:config/applicationContext-*.xml", "classpath:services/ext/service-*.xml" })
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
public class UserServiceTest extends AbstractTransactionalJUnit4SpringContextTests {

    @Resource
    private IUserService userService;

    @Test
    public void testAddOpinion1() {
        userService.downloadCount(1);
        System.out.println(1);
    }

    @Test
    public void testAddOpinion2() {
        userService.downloadCount(2);
        System.out.println(2);
    }
}

AbstractTransactionalJUnit4SpringContextTests:这个类为我们解决了在web.xml中配置OpenSessionInview所解决的session生命周期延长的问题,所以要继承这个类。该类已经在类级别预先配置了好了事物支持,因此不必再配置@Transactional和@RunWith

4)继承

package com.test;

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;

@ContextConfiguration(locations = { "classpath:config/applicationContext-*.xml", "classpath:services/ext/service-*.xml" })
@TransactionConfiguration(transactionManager = "transactionManager")
public class BaseTestCase extends AbstractTransactionalJUnit4SpringContextTests {

}

package com.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.springframework.test.annotation.Rollback;

public class UserServiceTest extends BaseTestCase {

    @Resource
    private IUserService userService;

    @Test
    public void testAddOpinion1() {
        userService.downloadCount(1);
        System.out.println(1);
    }

    @Test
    @Rollback(false)
    public void testAddOpinion2() {
        userService.downloadCount(2);
        System.out.println(2);
    }
}

5)综合

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TransactionConfiguration
@Transactional
public class PersonDaoTransactionUnitTest extends AbstractTransactionalJUnit4SpringContextTests {

    final Logger logger = LoggerFactory.getLogger(PersonDaoTransactionUnitTest.class);

    protected static int SIZE = 2;
    protected static Integer ID = new Integer(1);
    protected static String FIRST_NAME = "Joe";
    protected static String LAST_NAME = "Smith";
    protected static String CHANGED_LAST_NAME = "Jackson";

    @Autowired
    protected PersonDao personDao = null;

    /**
     * Tests that the size and first record match what is expected before the transaction.
     */
    @BeforeTransaction
    public void beforeTransaction() {
        testPerson(true, LAST_NAME);
    }

    /**
     * Tests person table and changes the first records last name.
     */
    @Test
    public void testHibernateTemplate() throws SQLException {
        assertNotNull("Person DAO is null.", personDao);

        Collection<Person> lPersons = personDao.findPersons();

        assertNotNull("Person list is null.", lPersons);
        assertEquals("Number of persons should be " + SIZE + ".", SIZE, lPersons.size());

        for (Person person : lPersons) {
            assertNotNull("Person is null.", person);

            if (ID.equals(person.getId())) {
                assertEquals("Person first name should be " + FIRST_NAME + ".", FIRST_NAME, person.getFirstName());
                assertEquals("Person last name should be " + LAST_NAME + ".", LAST_NAME, person.getLastName());

                person.setLastName(CHANGED_LAST_NAME);

                personDao.save(person);
            }
        }
    }

    /**
     * Tests that the size and first record match what is expected after the transaction.
     */
    @AfterTransaction
    public void afterTransaction() {
        testPerson(false, LAST_NAME);
    }

    /**
     * Tests person table.
     */
    protected void testPerson(boolean beforeTransaction, String matchLastName) {
        List<Map<String, Object>> lPersonMaps = simpleJdbcTemplate.queryForList("SELECT * FROM PERSON");

        assertNotNull("Person list is null.", lPersonMaps);
        assertEquals("Number of persons should be " + SIZE + ".", SIZE, lPersonMaps.size());

        Map<String, Object> hPerson = lPersonMaps.get(0);

        logger.debug((beforeTransaction ? "Before" : "After") + " transaction.  " + hPerson.toString());

        Integer id = (Integer) hPerson.get("ID");
        String firstName = (String) hPerson.get("FIRST_NAME");
        String lastName = (String) hPerson.get("LAST_NAME");

        if (ID.equals(id)) {
            assertEquals("Person first name should be " + FIRST_NAME + ".", FIRST_NAME, firstName);
            assertEquals("Person last name should be " + matchLastName + ".", matchLastName, lastName);
        }
    }

}

@BeforeTransaction在事务之前执行

@AfterTransaction在事务之后执行

@NotTransactional不开启事务

好了,本篇作为Junit补充就说到这里了,希望大家多多分享经验哦。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
2年前
JFinal的junit单元测试支持
在jfinal开发中不能直接使用junit单元测试,所以写了以下工具。原理是在运行junit测试方法之前启动jfinal的插件,运行完成后关闭插件。importorg.junit.After;importorg.junit.Before;importcom.jfinal.config.Constants;
Stella981 Stella981
2年前
Junit
junit4.x(1)、使用junit4.x版本进行单元测试时,不用测试类继承TestCase父类,因为,junit4.x全面引入了Annotation来执行我们编写的测试。\4\(2)、junit4.x版本,引用了注解的方式,进行单元测试;(3)、junit4.x版本我们常用的注解:A、@Before注解:与junit3.
javalover123 javalover123
9个月前
Testng和Junit5多线程并发测试对比
最近测试一个开源项目,发现生成的全局id有重复,也没有单元测试,就准备贡献个PR。想到多线程并发测试,根据经验,第一想法是用Testng,后面看了下Junit5也有实验性支持了,就对比下(以maven为例)
Python进阶者 Python进阶者
2个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这