Date-05-springs中使用Junit

一.IDEA 創(chuàng)建 JUnit

IDEA 下創(chuàng)建 JUnit,需要首先安裝JUnit插件,步驟如下:
【File -> settings -> Plugis -> Browse repositories ->輸入JUnit ->選擇JUnit Generator V2.0 安裝 ->重啟IDEA】


image.png

二.JUnit的使用

1.在程序中引入spring-test.jar

<!--junit測試依賴-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.0.10.RELEASE</version>
      <scope>test</scope>
    </dependency>

2.建一個類生成構(gòu)造方法

public class Max {
    private int a;
    private int b;

    public Max(int a, int b) {
        this.a = a;
        this.b = b;
    }
    public int getMax(){
        return a>b?a : b;
    }
}

3.在bean配置文件中添加依賴注入

   <bean id="max" class="com.spring.quickstart.Max">
        <constructor-arg name="a" value="5"/>
        <constructor-arg name="b" value="3"/>
    </bean>

4.IDEA中ctrl+shift+T選擇create new Test,Test_library選擇Junit4,勾選需要測試的方法然后ok
image
5.在生成的測試類外添加注解
  • 注:@RunWith:用于指定junit運行環(huán)境,是junit提供給其他框架測試環(huán)境接口擴展,為了便于使用spring的依賴注入,spring提供了org.springframework.test.context.junit4.SpringJUnit4ClassRunner作為Junit測試環(huán)境
    @ContextConfiguration({"classpath:applicationContext.xml","classpath:spring/buyer/applicationContext-service.xml"})
    導(dǎo)入配置文件,這里我的applicationContext配置文件是根據(jù)模塊來分類的。如果有多個模塊就引入多個“applicationContext-service.xml”文件。如果所有的都是寫在“applicationContext.xml”中則這樣導(dǎo)入:
    @ContextConfiguration(locations = "classpath:applicationContext.xml")
//指定單元測試環(huán)境
@RunWith(SpringJUnit4ClassRunner.class)
//指定配置文件路徑
@ContextConfiguration(locations = {"/spring.xml"})
public class MaxTest {
    //自定注入Max
    @Autowired
    private Max max;

    @Test
    public void getMax() {
        assertEquals(5,max.getMax() );
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容