MyBatis-Plus 如何單元測試的實現(xiàn)
最近項目中使用了 MyBatis-Plus,點擊看官方文檔。
使用一個新的框架,首先是驗證框架的使用。
使用 MyBatis-Plus,首先就驗證一下能否成功操作(CRUD)數(shù)據(jù)庫。
如何通過不用啟動項目,然后可以測試 MyBatis-Plus 查詢數(shù)據(jù)。
所以首要想到的是單元測試 @Test
第一步
通過 MyBatis-Plus 的代碼生成工具生成數(shù)據(jù)庫表對應(yīng)的文件
MyBatis-Plus 對于單表操作,有一個內(nèi)置的 mapper 接口方法,service 的接口我暫時沒使用并沒驗證過。
使用過 MyBatis 的應(yīng)該都知道,在 service 層使用 mapper.java 來操作數(shù)據(jù)庫,并且 mapper.xml 里面是有對應(yīng)的查詢?nèi)肟凇?br />
-- service
public class EntityServiceImp{
@Autowired
private EntityMapper mapper;
public void test(){
// 服務(wù)層調(diào)用 mapper.java 中的 selectEntityList 方法
mapper.selectEntityList(map);
}
}
-- mapper.java
public interface EntityMapper {
// mapper.xml 有一個id='selectEntityList' 的 select 塊
List<entity> selectEntityList(Map<String, Object> map);
}
--mapper.xml
<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 這么麻煩,可通過調(diào)用內(nèi)置一些單表的接口方法。
第二步
在 src/test/java 下面創(chuàng)建測試用例
@RunWith(SpringRunner.class)
@SpringBootTest
public class DbTest {
@Autowired
private LogYjxxMapper logYjxxMapper;
@Test
public void test2() {
// selectList 是內(nèi)置的方法,logYjxxMapper中并不需要自己定義 selectList 這么一個方法
// selectList括號里的參數(shù)是條件構(gòu)造器,可參看官方文檔
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 了。
到此這篇關(guān)于MyBatis-Plus 如何單元測試的實現(xiàn)的文章就介紹到這了,更多相關(guān)MyBatis-Plus 單元測試內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在Spring?Boot使用Undertow服務(wù)的方法
Undertow是RedHAT紅帽公司開源的產(chǎn)品,采用JAVA開發(fā),是一款靈活,高性能的web服務(wù)器,提供了NIO的阻塞/非阻塞API,也是Wildfly的默認Web容器,這篇文章給大家介紹了在Spring?Boot使用Undertow服務(wù)的方法,感興趣的朋友跟隨小編一起看看吧2023-05-05
maven中自定義MavenArchetype的實現(xiàn)
Maven自身提供了許多Archetype來方便用戶創(chuàng)建Project,為了避免在創(chuàng)建project時重復(fù)的拷貝和修改,我們通過自定義Archetype來規(guī)范顯得還蠻有必要,下面就來介紹一下,感興趣的可以了解一下2025-01-01
SpringMVC攔截器實現(xiàn)監(jiān)聽session是否過期詳解
這篇文章主要介紹了SpringMVC攔截器實現(xiàn)監(jiān)聽session是否過期詳解,還是比較不錯的,這里分享給大家,供需要的朋友參考。2017-11-11
SpringBoot實現(xiàn)熱部署的方式總結(jié)
所謂熱部署,就是在應(yīng)用正在運行的時候升級軟件,卻不需要重新啟動應(yīng)用,對于Java來說,熱部署就是在運行時更新Java類文件,本文將深入探討SpringBoot有哪些方式可以實現(xiàn)熱部署,感興趣的朋友可以小編一探討學習2023-06-06

