詳解springboot中junit回滾
springboot中使用junit編寫單元測試,并且測試結(jié)果不影響數(shù)據(jù)庫。
pom引入依賴
如果是IDE生成的項目,該包已經(jīng)默認(rèn)引入。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
數(shù)據(jù)庫原始數(shù)據(jù)

原始數(shù)據(jù)
編寫單元測試
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);
}
}
結(jié)果數(shù)據(jù)

結(jié)果數(shù)據(jù)
結(jié)論
可以看出code=001001的數(shù)據(jù)沒有更改,而code=001003的數(shù)據(jù)修改成功?;仡^看代碼:
@Transactional表示該方法整體為一個事務(wù),
@Rollback表示事務(wù)執(zhí)行完回滾,支持傳入一個參數(shù)value,默認(rèn)true即回滾,false不回滾。
該注解一樣支持對類的注解,若如此做,對整個class的方法有效。

注解在class上
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java實現(xiàn)將Word轉(zhuǎn)換成Html的示例代碼
在業(yè)務(wù)中,常常會需要在瀏覽器中預(yù)覽Word文檔,或者需要將Word文檔轉(zhuǎn)成HTML文件保存,本文主要為大家詳細(xì)介紹了Java實現(xiàn)Word轉(zhuǎn)換成Html的相關(guān)方法,希望對大家有所幫助2024-02-02
解決springboot+activemq啟動報注解錯誤的問題
這篇文章主要介紹了解決springboot+activemq啟動報注解錯誤的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
后端返回各種圖片形式在前端的轉(zhuǎn)換及展示方法對比
這篇文章主要給大家介紹了關(guān)于后端返回各種圖片形式在前端的轉(zhuǎn)換及展示方法對比的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2023-06-06
MyBatis3傳遞多個參數(shù)(Multiple Parameters)
這篇文章主要介紹了MyBatis3傳遞多個參數(shù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
mall整合SpringSecurity及JWT認(rèn)證授權(quán)實戰(zhàn)下
這篇文章主要為大家介紹了mall整合SpringSecurity及JWT認(rèn)證授權(quán)實戰(zhàn)第二篇,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
使用springboot單元測試對weblistener的加載測試
這篇文章主要介紹了使用springboot單元測試對weblistener的加載測試,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10

