日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

SSM中怎样使用JUnit4+spring-test编写单元测试

發布時間:2025/3/19 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SSM中怎样使用JUnit4+spring-test编写单元测试 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

場景

在進行正式業務前,往往要編寫單元測試。

實現

導包

如果你使用Maven構建項目,那么就自己搜索依賴。

這里假如你沒有使用Maven,所以你需要導包,除了正常的SSM所相關的包

你還需要導入

junit的jar包、spring-test的jar包。

jar包下載

https://download.csdn.net/download/badao_liumang_qizhi/10862195

編寫測試類

一般會在util包下新建測試類

這里是InsertTest.java

package com.badao.test;import java.util.List;import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import com.badao.mapper.UserMapper; import com.badao.pojo.User; import com.badao.util.Page; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;//使用junit4測試報錯導這個包 @RunWith(SpringJUnit4ClassRunner.class)//使用junit4進行測試 @ContextConfiguration("classpath:applicationContext.xml")//加載配置文件 public class InsertTest {@Autowired//自動注入private UserMapper userMapper;@Test//標明是測試方法@Rollback(false)? //標明使用完此方法后事務不回滾,true時為回滾public void testAdd() {for (int i = 0; i < 100; i++) {User user = new User();user.setName("user"+i);userMapper.addUser(user);}}@Testpublic void testTotal() {int total = userMapper.total();System.out.println(total);}@Testpublic void testList() {Page p = new Page();p.setStart(2);p.setCount(3);List<User> cs=userMapper.selectAllUser(p);for (User c : cs) {System.out.println(c.getName());}} }

執行

單元測試類中有多個單元測試的方法,在Eclipse的左邊項目目錄中找到單元測試類,然后找到要執行單元測試的方法,右鍵run? as -- JUnit Test 或者 debug as JUnit Test(可走斷點)


結果

這里執行向數據庫里添加100條數據操作

?@Test//標明是測試方法@Rollback(false)? //標明使用完此方法后事務不回滾,true時為回滾public void testAdd() {for (int i = 0; i < 100; i++) {User user = new User();user.setName("user"+i);userMapper.addUser(user);}}

注意

如果@RunWith(SpringJUnit4ClassRunner.class)//使用junit4進行測試

報錯

參照:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/85101633

@ContextConfiguration("classpath:applicationContext.xml") //加載配置文件

spring的配置文件的位置是在src下。

總結

以上是生活随笔為你收集整理的SSM中怎样使用JUnit4+spring-test编写单元测试的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。