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運(yùn)行環(huán)境,是junit提供給其他框架測試環(huán)境接口擴(kuò)展,為了便于使用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() );
}
}
- 注:@RunWith:用于指定junit運(yùn)行環(huán)境,是junit提供給其他框架測試環(huán)境接口擴(kuò)展,為了便于使用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")