spring集成了单元测试:
当spring整合了JUnit4后我们不仅仅通过@Test来测试,可以省去很多代码。
一、spring整合JUnit4
第一步:引入spring相关针对测试的依赖:spring-test.jar
第二步:创建测试类,使用注解方式完成测试单元
import com.fan.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.SQLException;
@RunWith(SpringJUnit4ClassRunner.class)//使用SpringJUnit4框架进行测试
@ContextConfiguration("classpath:spring.xml")//注解形式加载xml配置文件
@Component
public class TestJdbc {
@Resource//注入service对象
private UserService userService;
//测试数据源连接
@Resource(name = "dataSource")
private DataSource dataSource;
@Test//测试数据源连接
public void getConnection2() throws SQLException {
System.out.println(dataSource);
System.out.println(dataSource.getConnection());
}
@Test//测试转账
public void test01(){
userService.accountMoney();
}
}
使用的注解说明:
第一个注解:
@RunWith 就是一个运行器
@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境
第二个注解:
方式一:
@ContextConfiguration :使用此注解加载xml配置文件
单个xml文件:
@ContextConfiguration(locations=“classpath:applicationContext.xml”)
多个xml文件时:
@ContextConfiguration(locations = { “classpath:spring1.xml”, “classpath:spring2.xml” })
方式二:
@ContextConfiguration(classes=configAop.class):使用注解加载配置类,代替配置文件
二、spring整合junit5:
spring5框架的代码是基于jdk8,运行时兼容jdk9.
第一步:引入junit5的相关jar:junit-jupiter-api
第二步:创建测试类,使用注解方式完成测试单元
import com.fan.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.SQLException;
/*@ExtendWith(SpringExtension.class)//使用SpringJUnit5框架进行测试,这里不同于springjunit4
@ContextConfiguration("classpath:spring.xml")//注解形式加载xml配置文件*/
@SpringJUnitConfig(locations = "classpath:spring.xml")//复合注解,代替以上两个注解
public class TestJdbc2 {
@Resource//注入service对象
private UserService userService;
//测试数据源连接
@Resource(name = "dataSource")
private DataSource dataSource;
@Test//测试数据源连接
public void getConnection2() throws SQLException {
System.out.println(dataSource);
System.out.println(dataSource.getConnection());
}
@Test//测试转账
public void test01(){
userService.accountMoney();
}
}
spring5还有一个新注解@SpringJUnitConfig:
@ExtendWith(SpringExtension.class)//使用SpringJUnit5框架进行测试,这里不同于springjunit4
@ContextConfiguration(“classpath:spring.xml”)//注解形式加载xml配置文件
@SpringJUnitConfig(locations = “classpath:spring.xml”)//复合注解,代替以上两个(@ExtendWith,@ContextConfiguration)注解。