springboot中使用junit編寫單元測(cè)試,并且測(cè)試結(jié)果不影響數(shù)據(jù)庫(kù)。
pom引入依賴
如果是ide生成的項(xiàng)目,該包已經(jīng)默認(rèn)引入。
1
2
3
4
5
|
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> |
數(shù)據(jù)庫(kù)原始數(shù)據(jù)
原始數(shù)據(jù)
編寫單元測(cè)試
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( "洛陽(yáng)市" ); 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ù)沒(méi)有更改,而code=001003的數(shù)據(jù)修改成功。回頭看代碼:
@transactional表示該方法整體為一個(gè)事務(wù),
@rollback表示事務(wù)執(zhí)行完回滾,支持傳入一個(gè)參數(shù)value,默認(rèn)true即回滾,false不回滾。
該注解一樣支持對(duì)類的注解,若如此做,對(duì)整個(gè)class的方法有效。
注解在class上
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.jianshu.com/p/d9d0abf317c0?utm_source=tuicool&utm_medium=referral