单元测试之:注解

JUnit4通过注解的方式来识别测试方法。目前支持的主要注解有:

  • @BeforeClass 全局只会执行一次,而且是第一个运行
  • @Before 在测试方法运行之前运行
  • @Test 测试方法
  • @After 在测试方法运行之后允许
  • @AfterClass 全局只会执行一次,而且是最后一个运行
  • @Ignore 忽略此方法

事务:@Rollback

使用 @Rollback 的好处是, 测试数据不会对数据库造成污染, 这一点是很重要的。但 @Rollback 其实也不是真正意义上的数据零污染, 如果数据库表的主键是自增长类型, 虽然发生了事务回滚, 但是主键的索引还是会递增的。
执行这个测试, 数据库是不会插入记录的, 如果把 @Rollback 改成 @Rollback(false), 数据库就会插入一条数据
@Rollback 需要 @Transactional 的支持 ( 我们知道, @Transactional 默认是会自动提交事务的 ), 如果没有 @Transactional 标注, 则事务就不会受 @Rollback 的控制。
(被测试方法不管是否被事务管理 @Transactional 。@Rollback都生效) 

例子如下:

package com.imooc.myo2o.service;

import com.imooc.myo2o.O2oApplication;
import com.imooc.myo2o.dto.ShopExecution;
import com.imooc.myo2o.entity.Shop;
import org.apache.commons.fileupload.FileItem;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.util.Date;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {O2oApplication.class})
@Transactional
@Rollback
public class ShopServiceTest {

    @Autowired
    private ShopService shopService;
    @Test

    public void insertShop(){
        Shop shop = new Shop();
        shop.setShopName("测试3");
        shop.setEnableStatus(0);
        shop.setOwnerId(8L);
        shop.setCreateTime(new Date());
        shop.setLastEditTime(new Date());
        ShopExecution shopExecution = shopService.addShop(shop, null);
        System.out.println(shopExecution.getShop().toString());
    }

}

如果去掉 @Transactional,将插入成功。

 

详细解释

https://www.cnblogs.com/shouke/p/10171253.html
原文链接:https://blog.csdn.net/lin9209/article/details/85331748

posted @ 2020-04-20 15:42  你猜lovlife  阅读(278)  评论(0)    收藏  举报