日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

08-spring整合 junit

發布時間:2025/5/22 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 08-spring整合 junit 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目錄

  • 一、spring整合 junit 問題解析
  • 二、Spring 整合 junit 的配置
    • 1.加入架包
    • 2.@Runwith
    • 3.@ContextConfiguration

一、spring整合 junit 問題解析

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

    1.加入架包

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test --><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.1.9.RELEASE</version><scope>test</scope></dependency>

    2.@Runwith

    使用 Junit 提供的一個注解把原來的 main 方法替換了,替換成 spring 提供的

    這里面要求的是一個字節碼,必須是繼承 Runner 這個類

    3.@ContextConfiguration

    告知 spring 的運行期,spring 和 ioc 創建是基于 xml 還是注解的,并且說明位置

    • @ContextConfiguration
      • locations:指定 xml 文件的位置,加上 classpath 關鍵字,表示在類路徑下
      • classes:指定注解類所在地理位置
    • 注意:當我們使用 spring 5.x 版本的時候,要求 Junit 的 jar 必須是 4.12 及以上
    package com.test;import com.config.JdbcConfig; import com.config.SpringConfiguration; import com.domain.Account; import com.service.IAccountService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpringConfiguration.class) public class AccountServiceTest {@AutowiredIAccountService as=null;@Testpublic void testFindAllAccount(){//3.執行方法List<Account> accounts = as.findAllAccount();for (Account account:accounts){System.out.println(account);}}}

    轉載于:https://www.cnblogs.com/zuiren/p/11437518.html

    《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

    總結

    以上是生活随笔為你收集整理的08-spring整合 junit的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。