色综合图-色综合图片-色综合图片二区150p-色综合图区-玖玖国产精品视频-玖玖香蕉视频

您的位置:首頁技術(shù)文章
文章詳情頁

如何用SpringBoot 進行測試

瀏覽:67日期:2023-04-07 14:38:49

普通測試

假設(shè)要測試一個工具類 StringUtil(com.rxliuli.example.springboottest.util.StringUtil)

/** * 用于測試的字符串工具類 * * @author rxliuli */public class StringUtil { /** * 判斷是否為空 * * @param string 要進行判斷的字符串 * @return 是否為 null 或者空字符串 */ public static boolean isEmpty(String string) { return string == null || string.isEmpty(); } /** * 判斷是否為空 * * @param string 要進行判斷的字符串 * @return 是否為 null 或者空字符串 */ public static boolean isNotEmpty(String string) { return !isEmpty(string); } /** * 判斷是否有字符串為空 * * @param strings 要進行判斷的一個或多個字符串 * @return 是否有 null 或者空字符串 */ public static boolean isAnyEmpty(String... strings) { return Arrays.stream(strings) .anyMatch(StringUtil::isEmpty); } /** * 判斷字符串是否全部為空 * * @param strings 要進行判斷的一個或多個字符串 * @return 是否全部為 null 或者空字符串 */ public static boolean isAllEmpty(String... strings) { return Arrays.stream(strings) .allMatch(StringUtil::isEmpty); }}

需要添加依賴 spring-boot-starter-test 以及指定 assertj-core 的最新版本

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency></dependencies><dependencyManagement> <dependencies> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.9.1</version> <scope>test</scope> </dependency> </dependencies></dependencyManagement>

這里指定 assertj-core 的版本是為了使用較新的一部分斷言功能(例如屬性 lambda 斷言)

/** * @author rxliuli */public class StringUtilTest { private String strNull = null; private String strEmpty = ''; private String strSome = 'str'; @Test public void isEmpty() { //測試 null assertThat(StringUtil.isEmpty(strNull)) .isTrue(); //測試 empty assertThat(StringUtil.isEmpty(strEmpty)) .isTrue(); //測試 some assertThat(StringUtil.isEmpty(strSome)) .isFalse(); } @Test public void isNotEmpty() { //測試 null assertThat(StringUtil.isNotEmpty(strNull)) .isFalse(); //測試 empty assertThat(StringUtil.isNotEmpty(strEmpty)) .isFalse(); //測試 some assertThat(StringUtil.isNotEmpty(strSome)) .isTrue(); } @Test public void isAnyEmpty() { assertThat(StringUtil.isAnyEmpty(strNull, strEmpty, strSome)) .isTrue(); assertThat(StringUtil.isAnyEmpty()) .isFalse(); } @Test public void isAllEmpty() { assertThat(StringUtil.isAllEmpty(strNull, strEmpty, strSome)) .isFalse(); assertThat(StringUtil.isAnyEmpty(strNull, strEmpty)) .isTrue(); }}

這里和非 SpringBoot 測試時沒什么太大的區(qū)別,唯一的一點就是引入 Jar 不同,這里雖然我們只引入了 spring-boot-starter-test,但它本身已經(jīng)幫我們引入了許多的測試相關(guān)類庫了。

Dao/Service 測試

從這里開始就和標準的 Spring 不太一樣了

首先,我們需要 Dao 層,這里使用 H2DB 和 SpringJDBC 做數(shù)據(jù)訪問層(比較簡單)。

依賴

<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId></dependency>

添加兩個初始化腳本

數(shù)據(jù)庫結(jié)構(gòu) db_schema.sql(db/db_schema.sql)

drop table if exists user;create table user ( id int auto_increment not null comment ’編號’, name varchar(20) not null comment ’名字’, sex boolean null comment ’性別’, age int null comment ’年齡’);

數(shù)據(jù)庫數(shù)據(jù) db_data.sql(db/db_data.sql)

insert into user (id, name, sex, age)values (1, ’琉璃’, false, 17), (2, ’月姬’, false, 1000);

為 SpringBoot 配置一下數(shù)據(jù)源及初始化腳本

spring: datasource: driver-class-name: org.h2.Driver platform: h2 schema: classpath:db/db_schema.sql data: classpath:db/db_data.sql

然后是實體類與 Dao

用戶實體類 User(com.rxliuli.example.springboottest.entity.User)

/** * @author rxliuli */public class User implements Serializable { private Integer id; private String name; private Boolean sex; private Integer age; public User() { } public User(String name, Boolean sex, Integer age) { this.name = name; this.sex = sex; this.age = age; } public User(Integer id, String name, Boolean sex, Integer age) { this.id = id; this.name = name; this.sex = sex; this.age = age; } //getter() and setter()}

用戶 Dao UserDao(com.rxliuli.example.springboottest.dao.UserDao)

/** * @author rxliuli */@Repositorypublic class UserDao { private final RowMapper<User> userRowMapper = (rs, rowNum) -> new User( rs.getInt('id'), rs.getString('name'), rs.getBoolean('sex'), rs.getInt('age') ); @Autowired private JdbcTemplate jdbcTemplate; /** * 根據(jù) id 獲取一個對象 * * @param id id * @return 根據(jù) id 查詢到的對象,如果沒有查到則為 null */ public User get(Integer id) { return jdbcTemplate.queryForObject('select * from user where id = ?', userRowMapper, id); } /** * 查詢?nèi)坑脩? * * @return 全部用戶列表 */ public List<User> listForAll() { return jdbcTemplate.query('select * from user', userRowMapper); } /** * 根據(jù) id 刪除用戶 * * @param id 用戶 id * @return 受影響行數(shù) */ public int deleteById(Integer id) { return jdbcTemplate.update('delete from user where id = ?', id); }}

接下來才是正事,測試 Dao 層需要加載 Spring 容器,自動回滾以避免污染數(shù)據(jù)庫。

/** * {@code @SpringBootTest} 和 {@code @RunWith(SpringRunner.class)} 是必須的,這里貌似一直有人誤會需要使用 {@code @RunWith(SpringJUnit4ClassRunner.class)},但其實并不需要了 * 下面的 {@code @Transactional} 和 {@code @Rollback}則是開啟事務(wù)控制以及自動回滾 * * @author rxliuli */@SpringBootTest@RunWith(SpringRunner.class)@Transactional@Rollbackpublic class UserDaoTest { @Autowired private UserDao userDao; @Test public void get() { int id = 1; User result = userDao.get(id); //斷言 id 和 get id 相同 assertThat(result) .extracting(User::getId) .contains(id); } @Test public void listForAll() { List<User> userList = userDao.listForAll(); //斷言不為空 assertThat(userList) .isNotEmpty(); } @Test public void deleteById() { int result = userDao.deleteById(1); assertThat(result) .isGreaterThan(0); }}

Web 測試

與傳統(tǒng)的 SpringTest 一樣,SpringBoot 也分為兩種。

獨立安裝測試:

手動加載單個 Controller,所以測試其他 Controller 中的接口會發(fā)生異常。但測試速度上較快,所以應(yīng)當優(yōu)先選擇。

集成 Web 環(huán)境測試:

將啟動并且加載所有的 Controller, 所以效率上之于 BaseWebUnitTest 來說非常低下, 僅適用于集成測試多個 Controller 時使用。

獨立安裝測試

主要是設(shè)置需要使用的 Controller 實例,然后用獲得 MockMvc 對象進行測試即可。

/** * @author rxliuli */@SpringBootTest@RunWith(SpringRunner.class)@Transactional@Rollbackpublic class UserControllerUnitTest { @Autowired private UserController userController; /** * 用于測試 API 的模擬請求對象 */ private MockMvc mockMvc; @Before public void before() { //模擬一個 Mvc 測試環(huán)境,獲取一個 MockMvc 實例 mockMvc = MockMvcBuilders.standaloneSetup(userController) .build(); } @Test public void testGet() throws Exception { //測試能夠正常獲取 Integer id = 1; mockMvc.perform( //發(fā)起 get 請求 get('/user/' + id) ) //斷言請求的狀態(tài)是成功的(200) .andExpect(status().isOk()) //斷言返回對象的 id 和請求的 id 相同 .andExpect(jsonPath('$.id').value(id)); } @Test public void listForAll() throws Exception { //測試正常獲取 mockMvc.perform( //發(fā)起 post 請求 post('/user/listForAll') ) //斷言請求狀態(tài) .andExpect(status().isOk()) //斷言返回結(jié)果是數(shù)組 .andExpect(jsonPath('$').isArray()) //斷言返回數(shù)組不是空的 .andExpect(jsonPath('$').isNotEmpty()); }}

集成 Web 環(huán)境測試

/** * @author rxliuli */@SpringBootTest@RunWith(SpringRunner.class)@Transactional@Rollbackpublic class UserControllerIntegratedTest { @Autowired private WebApplicationContext context; /** * 用于測試 API 的模擬請求對象 */ private MockMvc mockMvc; @Before public void before() { //這里把整個 WebApplicationContext 上下文都丟進去了,所以可以測試所有的 Controller mockMvc = MockMvcBuilders.webAppContextSetup(context) .build(); } @Test public void testGet() throws Exception { //測試能夠正常獲取 Integer id = 1; mockMvc.perform( //發(fā)起 get 請求 get('/user/' + id) ) //斷言請求的狀態(tài)是成功的(200) .andExpect(status().isOk()) //斷言返回對象的 id 和請求的 id 相同 .andExpect(jsonPath('$.id').value(id)); } @Test public void listForAll() throws Exception { //測試正常獲取 mockMvc.perform( //發(fā)起 post 請求 post('/user/listForAll') ) //斷言請求狀態(tài) .andExpect(status().isOk()) //斷言返回結(jié)果是數(shù)組 .andExpect(jsonPath('$').isArray()) //斷言返回數(shù)組不是空的 .andExpect(jsonPath('$').isNotEmpty()); }}

總結(jié)

其實上面的測試類的注解感覺都差不多,我們可以將一些普遍的注解封裝到基類,然后測試類只要繼承基類就能得到所需要的環(huán)境,吾輩自己的測試基類在 src/test/common 下面,具體使用方法便留到下次再說吧

以上代碼已全部放到 GitHub 上面,可以直接 clone 下來進行測試

到此這篇關(guān)于如何用SpringBoot 進行測試的文章就介紹到這了,更多相關(guān)SpringBoot 測試內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 波多野结衣一区二区 三区 波多野结衣一区二区三区88 | 中文字幕欧美在线观看 | 欧美一级毛片高清免费观看 | 日韩亚洲人成网站在线播放 | 成人一级片在线观看 | 成年人在线视频 | 一区二区三区精品视频 | 99免费在线| 日韩一区二区在线播放 | 亚洲免费高清视频 | 99久久精品免费观看区一 | 日本一级爽毛片在线看 | 欧美一区二区三区久久综 | 欧美a毛片 | 一级欧美一级日韩 | 爱视频福利广场 | 成人欧美精品久久久久影院 | a欧美在线| 免费a网址 | 国产人成午夜免费噼啪视频 | 在线欧美视频 | 成人免费观看一区二区 | 欧美成年免费a级 | 精品国产不卡一区二区三区 | 久久久久久久久免费影院 | 草草视频手机在线观看视频 | 一区二区三区高清视频在线观看 | 久久免费精彩视频 | 亚洲丝袜另类 | 精品国产亚洲人成在线 | 久久在线视频播放 | 性配久久久 | www.成人在线视频 | 97视频在线观看免费视频 | 在线亚洲精品中文字幕美乳 | 午夜mm131美女做爰视频 | 国产精品成人久久久久 | 欧美一级毛片兔费播放 | 欧美黄色特级视频 | 国产成人综合精品一区 | 涩里番资源网站在线观看 |