说明
使用 junit进行spring测试
环境依赖
junit4以上,需要
junit-xxx.jarspring5以上,需要
spring-test-xxx.jar
传统工程
需要以下jar包:
- junit-4.12.jar
- spring-test-5.3.1.jar
maven 环境
添加以下依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.1<</version>
</dependency>
注解
RunWith
使用 @RunWith(SpringJUnit4ClassRunner.class) 注解,表示运行于Spring测试环境
加载配置文件
使用 @ContextConfiguration注解引入多个配置文件
单个文件:
@ContextConfiguration(Locations=“classpath:applicationContext.xml”)
@ContextConfiguration(classes = SimpleConfiguration.class)
多个文件:
@ContextConfiguration(locations = { “classpath:spring1.xml”, “classpath:spring2.xml” })
测试类
import com.etc.pojo.Orders;
import com.etc.service.OrdersService;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Date;
import java.util.UUID;
//让测试运行于Spring测试环境
@RunWith(SpringJUnit4ClassRunner.class)
//spring配置文件
@ContextConfiguration("classpath:applicationContext.xml")
public class Test {
@Autowired
private OrdersService service ;
@org.junit.Test
public void test(){
String uuid= UUID.randomUUID().toString().replace("-","");
Orders orders = new Orders();
orders.setId(uuid);
orders.setNum("1");
orders.setDatetime(new Date());
orders.setReceiver("李雷");
orders.setTotalPrice(5000.0);
service.add(orders);
}
}