Sping中使用Junit進行測試


分析:

1、應用程序的入口
  main方法
2、junit單元測試中,沒有main方法也能執行
  junit集成了一個main方法
  該方法就會判斷當前測試類中哪些方法有 @Test注解
  junit就讓有Test注解的方法執行
3、junit不會管我們是否采用spring框架
  在執行測試方法時,junit根本不知道我們是不是使用了spring框架
  所以也就不會為我們讀取配置文件/配置類創建spring核心容器
4、由以上三點可知
  當測試方法執行時,沒有Ioc容器,就算寫了Autowired注解,也無法實現注入

 

junit給我們暴露了一個注解,可以讓我們替換掉它的運行器

這時,我們需要依靠spring框架,因為它提供了一個運行器,可以讀取配置文件(或注解)來創建容器。

我們只需要告訴它配置文件在哪就行了。

 

pom.xml中添加依賴

 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.6.RELEASE</version>
            <scope>provided</scope>  
</dependency>
<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
</dependency>
<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>test</scope>
</dependency>    
 
         
/**
* 使用Junit單元測試:測試我們的配置
* Spring整合junit的配置
* 1、導入spring整合junit的jar(坐標)
* 2、使用Junit提供的一個注解把原有的main方法替換了,替換成spring提供的
* @Runwith
* 3、告知spring的運行器,spring和ioc創建是基於xml還是注解的,並且說明位置
* @ContextConfiguration
* locations:指定xml文件的位置,加上classpath關鍵字,表示在類路徑下
* classes:指定注解類所在地位置
*
* 當我們使用 spring 5.x 版本的時候, 要求junit的jar必須是 4.12 及以上
*/
//@RunWith就是一個運行器  
//@RunWith(JUnit4.class)就是指用JUnit4來運行 
//@RunWith(SpringJUnit4ClassRunner.class),讓測試運行於Spring測試環境 
//@RunWith(Suite.class)的話就是一套測試集合 
@RunWith(SpringJUnit4ClassRunner.class
) @ContextConfiguration(locations = {"classpath:bean.xml"})//加載配置文件 public class AccountServiceTest { @Autowired private IAccountService as; @Test public void testFindOne() { //3.執行方法 //ApplicationContext ac= new ClassPathXmlApplicationContext ("bean.xml"); // as=ac.getBean ("accountService",IAccountService.class); Account account = as.findAccountById(1); System.out.println(account); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM