day03 spring中使用Junit

1.配置Junit依賴

將下面這段代碼添加到項(xiàng)目的pom.xml文件的<dependencies>標(biāo)記中

<!--junit測(cè)試依賴-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.0.10.RELEASE</version>
      <scope>test</scope>
    </dependency>
2.新建一個(gè)類生成構(gòu)造方法然后自定義待測(cè)試方法
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,勾選需要測(cè)試的方法然后ok
5.在生成的測(cè)試類外添加@@RunWith()和@ContextConfiguration()注解

類中自定義注入id,然后在方法中進(jìn)行斷言,運(yùn)行方法

//指定單元測(cè)試環(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() );
    }
}

(locations指向你創(chuàng)建的bean配置文件)

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

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

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