Junit寫法及與spring整合過(guò)程詳解
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整合:
不需要手動(dòng)創(chuàng)建Spring容器, 自動(dòng)把bean注入到測(cè)試類
1、導(dǎo)入spring-test的依賴, 需要junit
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.3.RELEASE</version></dependency>
2、在測(cè)試類使用spring-test的注解
@RunWith(class)
@ContextConfiguration(指定配置文件)
//測(cè)試類運(yùn)行的環(huán)境,在spring環(huán)境下運(yùn)行,在測(cè)試類, 注入Spring容器的bean@RunWith(SpringJUnit4ClassRunner.class)//在創(chuàng)建spring容器時(shí),指定加載哪個(gè)配置文件 - - 相當(dāng)于之前的手動(dòng)獲取對(duì)象@ContextConfiguration('classpath:applicationContext.xml')public class UserServiceImplTest { @Autowired //注入IUserService private IUserService userService; @Test public void testFindUserById() { userService.findUserById(2); }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. .NET 中配置從xml轉(zhuǎn)向json方法示例詳解2. ASP錯(cuò)誤捕獲的幾種常規(guī)處理方式3. 詳解php如何合并身份證正反面圖片為一張圖片4. Laravel中數(shù)據(jù)庫(kù)遷移操作的示例詳解5. python 用遞歸實(shí)現(xiàn)通用爬蟲(chóng)解析器6. npm下載慢或下載失敗問(wèn)題解決的三種方法7. Python 如何將字符串每?jī)蓚€(gè)用空格隔開(kāi)8. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁(yè)的方法9. ASP編碼必備的8條原則10. python基于opencv批量生成驗(yàn)證碼的示例
