buguge - Keep it simple,stupid

知识就是力量,但更重要的,是运用知识的能力why buguge?

导航

junit/spring-test @Rollback的使用

在junit的testcase里,要使用@Rollback,必须配合@Transactional用

必须强调一下:开发人员要写单元测试用例,养成习惯。谁也不能保证自己的代码不会有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;

@Slf4j
public class TestIDriverServiceImpl extends BaseTest {
    @Autowired
    DriverServiceImpl driverService;

    @Test
    @Transactional
    @Rollback(true) // boolean value 默认值是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;

@RunWith(SpringRunner.class)
@SpringBootTest
//@TestPropertySource()
public class BaseTest { }

 

posted on 2020-07-03 12:14  buguge  阅读(2126)  评论(0编辑  收藏  举报