最近項目中使用了 MyBatis-Plus,點擊看官方文檔。
使用一個新的框架,首先是驗證框架的使用。
使用 MyBatis-Plus,首先就驗證一下能否成功操作(CRUD)數據庫。
如何通過不用啟動項目,然后可以測試 MyBatis-Plus 查詢數據。
所以首要想到的是單元測試 @Test
第一步
通過 MyBatis-Plus 的代碼生成工具生成數據庫表對應的文件
MyBatis-Plus 對于單表操作,有一個內置的 mapper 接口方法,service 的接口我暫時沒使用并沒驗證過。
使用過 MyBatis 的應該都知道,在 service 層使用 mapper.java 來操作數據庫,并且 mapper.xml 里面是有對應的查詢入口。
-- service
1
2
3
4
5
6
7
8
|
public class EntityServiceImp{ @Autowired private EntityMapper mapper; public void test(){ // 服務層調用 mapper.java 中的 selectEntityList 方法 mapper.selectEntityList(map); } } |
-- mapper.java
1
2
3
4
|
public interface EntityMapper { // mapper.xml 有一個id='selectEntityList' 的 select 塊 List<entity> selectEntityList(Map<String, Object> map); } |
--mapper.xml
1
2
3
4
5
6
7
|
< mapper namespace = "com.example.mapper.EntityMapper" > < resultMap id = "BaseResultMap" type = "com.example.pojo.Entity" ></ resultMap > < select id = "selectEntityList" resultMap = "BaseResultMap" parameterType = "map" > select * from entity where ..... </ select > < mapper > |
然而使用 MyBatis-Plus,對于單表操作,不需要像 MyBatis 這么麻煩,可通過調用內置一些單表的接口方法。
第二步
在 src/test/java 下面創建測試用例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@RunWith (SpringRunner. class ) @SpringBootTest public class DbTest { @Autowired private LogYjxxMapper logYjxxMapper; @Test public void test2() { // selectList 是內置的方法,logYjxxMapper中并不需要自己定義 selectList 這么一個方法 // selectList括號里的參數是條件構造器,可參看官方文檔 List<LogYjxx> yjxxLoglist = logYjxxMapper.selectList( new QueryWrapper<LogYjxx>() .eq( "lx" , YjxxConstant.LX_SF) .and(i -> i.in( "zt" , 2 , 3 ).or().isNull( "zt" )) ); for (LogYjxx logYjxx : yjxxLoglist) { System.out.println(logYjxx); } } } |
重點: 類上方的兩個注解(@RunWith(SpringRunner.class) @SpringBootTest)很重要,不要漏了。
好了,通過以上兩步,就可以很順利的驗證自己的 sql 了。
到此這篇關于MyBatis-Plus 如何單元測試的實現的文章就介紹到這了,更多相關MyBatis-Plus 單元測試內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/godbrian/article/details/89554718