首頁  >  文章  >  Java  >  springboot中junit回滾的作用是什麼

springboot中junit回滾的作用是什麼

PHPz
PHPz轉載
2023-05-16 08:28:131094瀏覽

springboot中使用junit編寫單元測試,且測試結果不影響資料庫。

pom引入依賴

如果是IDE產生的項目,則該套件已經預設為引入。

<dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-test</artifactid>
      <scope>test</scope>
    </dependency>

資料庫原始資料

springboot中junit回滾的作用是什麼

原始資料

#編寫單元測試

package com.mos.quote;

import com.mos.quote.model.Area;
import com.mos.quote.service.IAreaService;
import org.junit.Assert;
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 java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class QuoteApplicationTests {

  @Autowired
  private IAreaService areaService;

  @Test
  public void contextLoads() {
  }

  @Test
  public void testUpdate(){
    Area area = new Area();
    area.setCode("001003");
    area.setName("洛阳市");
    Integer result = areaService.update(area);
    Assert.assertEquals(1, (long)result);
  }

  @Test
  @Transactional
  @Rollback
  public void testUpdate4Rollback(){
    Area area = new Area();
    area.setCode("001001");
    area.setName("郑州市123");
    Integer result = areaService.update(area);
    Assert.assertEquals(1, (long)result);
  }

}

結果資料

springboot中junit回滾的作用是什麼

結果資料

#結論

可以看出code=001001的資料沒有更改,而code=001003的資料修改成功。回頭看程式碼:

@Transactional表示該方法整體為一個事務,

#@Rollback表示事務執行完回滾,支援傳入一個參數value,預設true即回滾,false不回滾。

該註解一樣支援對類別的註解,若如此做,對整個class的方法有效。

springboot中junit回滾的作用是什麼

註解在class上

以上是springboot中junit回滾的作用是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除