Spring整合Junit的測試

2021-10-12 06:55:49 字數 1523 閱讀 8846

在測試類中,每個測試方法都有以下兩行**:

new(

"bean.xml");

iaccountservice as = ac.

getbean

("accountservice"

,iaccountservice.

class);

這兩行**的作用是獲取容器,如果不寫的話,直接會提示空指標異常。所以又不能輕易刪掉。

①、匯入spring整合junit的座標

>

>

org.springframeworkgroupid

>

>

spring-testartifactid

>

>

5.0.2.releaseversion

>

dependency

>

>

>

junitgroupid

>

>

junitartifactid

>

>

4.12version

>

>

testscope

>

dependency

>

②、使用@runwith註解替換原來的執行期

@runwith

(springjunit4classrunner.

class

)public

class

springjunittest

③、使用@contextconfiguration指定配置檔案或配置類

@runwith

(springjunit4classrunner.

class

)//載入spring核心配置檔案

//載入spring核心配置類

@contextconfiguration

(classes =

)public

class

springjunittest

④、使用@autowired注入需要測試的物件

@runwith

(springjunit4classrunner.

class

)@contextconfiguration

(classes =

)public

class

springjunittest

⑤、建立測試方法進行測試

@runwith

(springjunit4classrunner.

class

)@contextconfiguration

(classes =

)public

class

springjunittest

}

spring 整合Junit,整合web

l 匯入jar包 基本 4 1 測試 spring test.jar 1.讓junit通知spring載入配置檔案 2.讓spring容器自動進行注入 l 修改測試類 package com.hcx import org.junit.test import org.junit.runner.runw...

Spring整合junit測試

spring提供spring test 3.2.0.release.jar 可以整合junit 優勢 可以簡化測試 不需要手動建立上下文 目標 測試spring的bean的某些功能 runwith springjunit4classrunner.class 固定寫法,junit整合spring的測試...

Spring整合Junit測試

spring整合junit是為了解決 重複和配置檔案多次載入的問題 解決的方法很簡單 第一步使用註解告訴spring配置檔案在哪 第二步使用註解讓spring載入配置檔案 要匯入的包有spring的aop和test,junit的單元測試包 contextconfiguration value cla...