Junit寫法及與spring整合過程詳解
junit之前的寫法:
//在Before中注入service類private IUserService userService; @Beforepublic void setUp() throws Exception {//使用xml的方式ApplicationContext applicationContext = new ClassPathXmlApplicationContext('applicationContext.xml');//使用注解的方式ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);userService = applicationContext.getBean(IUserService.class); }
Spring與junit整合:
不需要手動創(chuàng)建Spring容器, 自動把bean注入到測試類
1、導(dǎo)入spring-test的依賴, 需要junit
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.3.RELEASE</version></dependency>
2、在測試類使用spring-test的注解
@RunWith(class)
@ContextConfiguration(指定配置文件)
//測試類運(yùn)行的環(huán)境,在spring環(huán)境下運(yùn)行,在測試類, 注入Spring容器的bean@RunWith(SpringJUnit4ClassRunner.class)//在創(chuàng)建spring容器時,指定加載哪個配置文件 - - 相當(dāng)于之前的手動獲取對象@ContextConfiguration('classpath:applicationContext.xml')public class UserServiceImplTest { @Autowired //注入IUserService private IUserService userService; @Test public void testFindUserById() { userService.findUserById(2); }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JavaEE SpringMyBatis是什么? 它和Hibernate的區(qū)別及如何配置MyBatis2. android 控件同時監(jiān)聽單擊和雙擊實例3. Python 忽略文件名編碼的方法4. 解決vue頁面刷新,數(shù)據(jù)丟失的問題5. Java Media Framework 基礎(chǔ)教程6. springboot項目整合druid數(shù)據(jù)庫連接池的實現(xiàn)7. python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作8. android studio實現(xiàn)簡單的計算器(無bug)9. 在Mac中配置Python虛擬環(huán)境過程解析10. Python趣味挑戰(zhàn)之用pygame實現(xiàn)簡單的金幣旋轉(zhuǎn)效果
