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配置文件)