日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

08-spring整合 junit

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

目錄

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

一、spring整合 junit 問題解析

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

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

    3.@ContextConfiguration

    告知 spring 的運行期,spring 和 ioc 創(chuàng)建是基于 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.執(zhí)行方法List<Account> accounts = as.findAllAccount();for (Account account:accounts){System.out.println(account);}}}

    轉(zhuǎn)載于:https://www.cnblogs.com/zuiren/p/11437518.html

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

    總結(jié)

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

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。