junit測試和spring整合
- 2019 年 10 月 30 日
- 筆記
版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
本文鏈接:https://blog.csdn.net/luo4105/article/details/72865519
Junit簡介
Junit是十分好的單元測試工具,根據敏捷開發中測試驅動開發的思想,開發前應該先寫單元測試和測試用例,再寫實現方法,這樣可以驗證方法的正確與否,同時對方法重構後,執行一下寫好的單元測試,也可以很明了的清楚重構是否損壞其他程式碼。
Eclipse默認帶有junit插件,沒有的說明版本太低,請自行百度Eclipse安裝junit
單元測試
單元測試就是單純的測試單一功能的實現,在單元測試中,不應該依賴spring容器之類的。
在項目中導入junit,寫好測試方法,前些加@Test就可以了
用eclispe開始創建測試用例

運行測試用例

集成測試
集成測試可以使用spring的推薦的測試工具:spring-test.jar
也可以使用:junit
使用junit測試
測試mybatis的dao介面
實際上是載入mybatis的配置文件,獲得mybatis的sqlsessionfactory和sqlsession,再獲得mapper介面對象,並執行測試方法。
public classUserMapperTest { private static SqlSessionFactory ssf = null; private static SqlSession sqlSession = null; private static UserMapper mapper = null; //要測試的mapper介面對象 static { // junit 找文件從src或WebContent上一級開始找,即classpath try { ssf = newSqlSessionFactoryBuilder().build(Resources.getResourceAsReader("com/lc/config/mybatis.xml")); sqlSession = ssf.openSession(); mapper = sqlSession.getMapper(UserMapper.class); }catch(IOException e) { e.printStackTrace(); } } @Test public void select() { List<User>userlist= mapper.select(); for (User user : userlist) { System.out.println(user); } } @Test public void delete() { if (mapper.delete(1) > 0) { sqlSession.rollback(); System.out.println("del success"); sqlSession.close(); } } }
測試service方法
實際上是載入spring配置,得到spring容器,在spring容器中拿到service的bean,並掉用其方法。
public classLogServiceTest { private LogService logService; @Before public void setUp() throws Exception { @SuppressWarnings("resource") ClassPathXmlApplicationContextcontext= newClassPathXmlApplicationContext( new String[] { "spring/spring-config.xml"}); context.start(); logService = context.getBean(LogService.class); } @Test public void testSelectOne() { Loglog= logService.selectOne(1); System.out.println(log); } @Test public void testSelect() { Loglog= newLog(); List<Log>list= logService.select(log); System.out.println(list); } @Test public void testSelectByPage() { Loglog= newLog(); PageInfo<Log>page= logService.selectByPage(log, null); System.out.println(JSON.toJSONString(page)); } @Test public void testInsert() { Loglog=newLog(); log.setUsername("xudong"); logService.insert(log); } }
測試controller
這裡實際上是模擬http請求去調用controller介面,判斷返回的數據是否正常
public classUserControllerTest { @Before public void setUp() throws Exception { } @Test public void testSelectOne() throws IOException { InputStreamis = new HttpUtil().doGet("http://localhost:8080/hotchPotch-web/system/user/selectOne?id=1"); Stringresult= newStreamUtil().inputStreamToString(is, "utf-8"); System.out.println(result); } class HttpUtil { InputStream doGet(String urlstr) throws IOException { URL url= new URL(urlstr); HttpURLConnection conn= (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); InputStream inputStream= conn.getInputStream(); return inputStream; } } class StreamUtil { public StringinputStreamToString(InputStream is, String charset)throwsIOException { byte[] bytes = newbyte[1024]; int byteLength = 0; StringBuffer sb = new StringBuffer(); while((byteLength = is.read(bytes)) != -1) { sb.append(new String(bytes, 0, byteLength, charset)); } return sb.toString(); } } }
說說缺點
1.每執行一個測試方法都要載入spring配置文件,如果spring容器中需要載入的bean十分多,那麼十分耗時。
2.資料庫數據改變後不能回滾。
使用spring-test.jar和junit4測試
優點是
1.只需載入一次spring配置文件
2.支援數據回滾
3.支援spring注入,不需要使用getBean的方式獲得spring容器的bean。
Transaction中的參數是事務bean的id
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring/spring-config.xml"}) @Transactional(transactionManager="txManager") public classLogServiceTest { @Resource private LogService logService; @Test public void testSelect() { Loglog= newLog(); List<Log>list= logService.select(log); System.out.println(list); } @Test @Rollback(true) public void testInsert() { Loglog=newLog(); log.setUsername("xudong2"); logService.insert(log); } }
Java中,根據註解是可以繼承的原理,我們可以抽象出載入Spring這些配置的註解在一個父類中,子類只需要專心寫好測試方法就可以。
父類
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring/spring-config.xml"}) @Transactional(transactionManager="txManager") public classSpringTestRunner { }
子類
public classLogServiceTestextendsSpringTestRunner { @Resource private LogService logService; @Test public void testSelect() { Loglog= newLog(); List<Log>list= logService.select(log); System.out.println(list); } @Test @Rollback(true) public void testInsert() { Loglog=newLog(); log.setUsername("xudong2"); logService.insert(log); } }
使用log4j輸出日誌
簡單方法
Spring配置會自動掃描源碼包下是否存在log4j.properties,只需要把log4j.properties放在源碼包下就可以了
改寫SpringJUnit4ClassRunner類
public classJUnit4ClassRunner extends SpringJUnit4ClassRunner { static{ try { Log4jConfigurer.initLogging("classpath:config/log4j.xml"); } catch (FileNotFoundException ex) { System.err.println("Cannot Initialize log4j"); } } publicJUnit4ClassRunner(Class<?> clazz) throwsInitializationError { super(clazz); } }
測試類用SpringJUnit4ClassRunner的運行
@RunWith(JUnit4ClassRunner.class)
