SSM中怎样使用JUnit4+spring-test编写单元测试
生活随笔
收集整理的這篇文章主要介紹了
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编写单元测试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: RunWith(SpringJUnit4
- 下一篇: SSM中实现分页与JUnit单元测试