文章目录
一、测试类中的问题和解决思路
1、问题
在测试类中,每个测试方法都有以下两行代码:
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。
2、整合思路
1、应用程序的入口
main方法
2、Junit单元测试中,没有main方法也能执行
Junit集成了一个main方法
该方法就会判断当前测试类中哪些方法有@Test注解
Junit就让有Test注解的方法执行
3、Junit不会管我们是否采用spring框架
在执行测试方法时,Junit根本不知道我们是不是使用了spring框架
所以也就不会为我们读取配置文件/配置类创建spring核心容器
4、由以上三点可知
当测试方法执行时,没有IOC容器,就算写了Autowired注解,也无法实现注入。
3、解决思路分析
针对上述问题,我们需要的是程序能自动帮我们创建容器。一旦程序能自动为我们创建 spring 容器,我们就无须手动创建了,问题也就解决了。
我们都知道,junit 单元测试的原理(在 web 阶段课程中讲过),但显然,junit 是无法实现的,因为它自己都无法知晓我们是否使用了 spring 框架,更不用说帮我们创建 spring 容器了。不过好在,junit 给我们暴露了一个注解,可以让我们替换掉它的运行器。
这时,我们需要依靠 spring 框架,因为它提供了一个运行器,可以读取配置文件(或注解)来创建容器。我们只需要告诉它配置文件在哪就行了。
二、配置步骤
1、导入spring整合Junit依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
2、使用@RunWith 注解替换原有运行器
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest {
}
3、使用@ContextConfiguration 指定 spring 配置文件的位置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
}
@ContextConfiguration 注解:
locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明
classes 属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。
4、使用@Autowired 给测试类中的变量注入数据
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
@Autowired
private IAccountService as ;
}
三、为什么不把测试类配到 xml 中
在解释这个问题之前,先解除大家的疑虑,配到 XML 中能不能用呢?
答案:是肯定的,没问题,可以使用。
那么为什么不采用配置到 xml 中的方式呢?
这个原因是这样的:
第一:当我们在 xml 中配置了一个 bean,spring 加载配置文件创建容器时,就会创建对象。
第二:测试类只是我们在测试功能时使用,而在项目中它并不参与程序逻辑,也不会解决需求上的问题,所以创建完了,并没有使用。那么存在容器中就会造成资源的浪费。
所以,基于以上两点,我们不应该把测试配置到 xml 文件中。
四、代码
1、持久层
public class AccountDao implements IAccountDao{
private QueryRunner runner;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public List<Account> findAllAccount() {
try {
return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Account findAccountById(Integer id) {
try {
return runner.query("select * from account where id=?",new BeanHandler<Account>(Account.class),id);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void saveAccount(Account account) {
try {
runner.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try {
runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void deleteAccount(Integer id) {
try {
runner.update("delete from account where id=?",id);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
2、业务层
/**
* 账户的业务层实现类
* @author
*
*/
public class AccountServiceImpl implements IAccountService{
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
public void deleteAccount(Integer id) {
accountDao.deleteAccount(id);
}
}
3、配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置service对象 -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<!-- 注入dao -->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配合dao -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDao">
<!-- 注入runner -->
<property name="runner" ref="runner"></property>
</bean>
<!-- 配置QueryRunner -->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!-- 注入数据源(构造方法注入) -->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 连接数据库的必备信息 -->
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy?useSSL=false&serverTimezone=UTC"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
4、测试类
//使用Junit单元测试配置:测试我们的配置是否正确
/**
* spring整合Junit的配置
* 1、导入spring整合Junit的jar或坐标
* <artifactId>spring-test</artifactId>
* 2、使用Junit提供的注解把原有的main方法替换,替换成spring提供的
* @Runwith(SpringJUnit4ClassRunner.class)
* 3、告知spring的运行器,spring和ioc创建是基于xml还是注解的,并说明位置
* @ContextConfiguration
* locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明
* classes 属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。
* 细节:
* 当我们使用spring 5.x版本的时候,要求Junit的jar包必须是4.10及以上。
* @ContextConfiguration(locations = "classpath:bean.xml")
* @ContextConfiguration(classes =SpringConfiguration.class)
* 4、使用@Autowired 给测试类中的变量注入数据
* @author
*
*/
//spring整合Junit的配置
@RunWith(SpringJUnit4ClassRunner.class)
//告知spring的运行器,spring和ioc创建是基于xml还是注解的,并说明位置
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest_Junit {
@Autowired //要它自动按照类型注入
private IAccountService as;
@Test//3、执行方法
public void testfindAll() {
List<Account> accounts = as.findAllAccount();
for(Account account:accounts) {
System.out.println(account);
}
}
@Test
public void testfindOne() {
Account account = as.findAccountById(2);
System.out.println(account);
}
@Test
public void testSaveAccount() {
Account account = new Account();
account.setName("ddd");
account.setMoney(4000.0f);
as.saveAccount(account);
}
@Test
public void testUpdateAccount() {
Account account = new Account();
account.setId(4);
account.setName("ddd");
account.setMoney(1000.0f);
as.updateAccount(account);
}
@Test
public void testDeleteAccount() {
as.deleteAccount(4);
}
}
5、补充
public class AccountServiceTest2_static {
private static ApplicationContext ac;
private static IAccountService as;
static {
ac = new ClassPathXmlApplicationContext("bean.xml");
as = ac.getBean("accountService",IAccountService.class);
}
@Test//3、执行方法
public void testfindAll() {
List<Account> accounts = as.findAllAccount();
for(Account account:accounts) {
System.out.println(account);
}
}
@Test
public void testfindOne() {
Account account = as.findAccountById(2);
System.out.println(account);
}
@Test
public void testSaveAccount() {
Account account = new Account();
account.setName("ddd");
account.setMoney(4000.0f);
as.saveAccount(account);
}
@Test
public void testUpdateAccount() {
Account account = new Account();
account.setId(4);
account.setName("ddd");
account.setMoney(1000.0f);
as.updateAccount(account);
}
@Test
public void testDeleteAccount() {
as.deleteAccount(4);
}
}