springboot中使用junit編寫單元測試,并且測試結果不影響數據庫。
pom引入依賴
如果是ide生成的項目,該包已經默認引入。
1
2
3
4
5
|
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> |
數據庫原始數據
原始數據
編寫單元測試
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
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); } } |
結果數據
結果數據
結論
可以看出code=001001的數據沒有更改,而code=001003的數據修改成功。回頭看代碼:
@transactional表示該方法整體為一個事務,
@rollback表示事務執行完回滾,支持傳入一個參數value,默認true即回滾,false不回滾。
該注解一樣支持對類的注解,若如此做,對整個class的方法有效。
注解在class上
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.jianshu.com/p/d9d0abf317c0?utm_source=tuicool&utm_medium=referral