junit/spring-test @Rollback的使用

必须强调一下:开发人员要写单元测试用例,养成习惯。谁也不能保证自己的代码不会有bug,也别光指望让QA给你指出来,出bug再反复改。

今天利用junit写一个testcase,因为要修改数据,所以为了不破坏原始数据,用到了@Rollback注解,发现执行完testcase后数据没回滚,直觉认为得配合@Transactional注解用。然后,看了一下@Rollback的javadoc,并没有明确提到@Transactional注解。

不过,经过测试,已经确定必须要有@Transactional注解。

@Transactional 在 spring-tx.jar 下, package:org.springframework.transaction.annotation

@Rollback 在spring-test.jar 下,package:org.springframework.test.annotation

在此做个记录。

testcase:

package com.emaxcard.car.modules.driver;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;

/**
 * 描    述:
 * <p>
 * 创 建 者: zhangym
 * 创建时间: 2019/11/18 14:41
 * 创建描述:
 * <p>
 * 修 改 者:
 * 修改时间:
 * 修改描述:
 * <p>
 * 审 核 者:
 * 审核时间:
 * 审核描述:
 */
@Slf4j
public class TestIDriverServiceImpl extends BaseTest {
    @Autowired
    DriverServiceImpl driverService;

    @Test
    @Transactional
    @Rollback(true)
    public void update() {
        Driver driver=driverService.getById(575L);
        System.out.println("--------------"+driver);
        driver.setFeeDay(BigDecimal.ONE);
        driverService.update(BeanMapper.map(driver,DriverVO.class));
        driver=driverService.getById(575L);
        System.out.println("--------------"+driver);
    }
}

BaseTest:

package com.emaxcard.car.modules;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * 描    述:
 * <p>
 * 创 建 者: jasonchen
 * 创建时间: 2019-11-16 14:18
 * 创建描述:
 * <p>
 * 修 改 者:
 * 修改时间:
 * 修改描述:
 * <p>
 * 审 核 者:
 * 审核时间:
 * 审核描述:
 */
@RunWith(SpringRunner.class)
@SpringBootTest
//@TestPropertySource()
public class BaseTest { }
原文地址:https://www.cnblogs.com/buguge/p/13229660.html