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

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

如何用SpringBoot 進(jìn)行測試

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

普通測試

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

/** * 用于測試的字符串工具類 * * @author rxliuli */public class StringUtil { /** * 判斷是否為空 * * @param string 要進(jìn)行判斷的字符串 * @return 是否為 null 或者空字符串 */ public static boolean isEmpty(String string) { return string == null || string.isEmpty(); } /** * 判斷是否為空 * * @param string 要進(jìn)行判斷的字符串 * @return 是否為 null 或者空字符串 */ public static boolean isNotEmpty(String string) { return !isEmpty(string); } /** * 判斷是否有字符串為空 * * @param strings 要進(jìn)行判斷的一個或多個字符串 * @return 是否有 null 或者空字符串 */ public static boolean isAnyEmpty(String... strings) { return Arrays.stream(strings) .anyMatch(StringUtil::isEmpty); } /** * 判斷字符串是否全部為空 * * @param strings 要進(jìn)行判斷的一個或多個字符串 * @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 的版本是為了使用較新的一部分?jǐn)嘌怨δ埽ɡ鐚傩?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ū)別,唯一的一點(diǎn)就是引入 Jar 不同,這里雖然我們只引入了 spring-boot-starter-test,但它本身已經(jīng)幫我們引入了許多的測試相關(guān)類庫了。

Dao/Service 測試

從這里開始就和標(biāo)準(zhǔn)的 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

然后是實(shí)體類與 Dao

用戶實(shí)體類 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)},但其實(shí)并不需要了 * 下面的 {@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 也分為兩種。

獨(dú)立安裝測試:

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

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

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

獨(dú)立安裝測試

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

/** * @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 實(shí)例 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 上下文都丟進(jìn)去了,所以可以測試所有的 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é)

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

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

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

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 日本免费小视频 | 高清在线亚洲精品国产二区 | 四虎免费大片aⅴ入口 | 国产高清一级毛片在线不卡 | 欧美一级精品高清在线观看 | 成人国产在线不卡视频 | 三级黄色网 | 欧美三级香港三级日本三级 | 日韩丝袜美腿 | 国产综合在线播放 | 亚洲视频观看 | 免费一级a毛片在线播放 | 国产一区二区高清在线 | 国产精选莉莉私人影院 | 欧美日中文字幕 | 国产成人精品一区二区不卡 | 色综合久久久久 | 一级片久久| 日本三级香港三级少妇 | 日韩特级黄色片 | 欧美成人另类69 | 中文字幕成人免费高清在线视频 | 91进入蜜桃臀在线播放 | 被老外玩爽的中国美女视频 | 国产成人午夜性视频影院 | 欧美另类极品 | 久久er热这里只有精品免费 | 99久久精品费精品国产一区二 | 欧美日韩高清观看一区二区 | 成人欧美一区二区三区视频xxx | 国产成人免费永久播放视频平台 | 欧美日韩视频精品一区二区 | 欧美日中文字幕 | 免费黄网在线观看 | 国产福利拍拍拍 | 国产在线观看免费 | 俺来也欧美亚洲a∨在线 | 中国黄色网址大全 | 特级毛片aaaa免费观看 | 成人亚洲网站 | 国产精品青草久久 |