【Spring】之Spring整合Junit-05

1 测试案例-使用 Spring 的 IOC 的实现账户的CRUD

1.1 环境搭建

1.1.1 创建Maven项目工程

在这里插入图片描述
项目工程结构图:
在这里插入图片描述

1.1.2 pom.xml中引入依赖

<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>commons-dbutils</groupId>
	<artifactId>commons-dbutils</artifactId>
	<version>1.4</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.38</version>
</dependency>
<dependency>
	<groupId>c3p0</groupId>
	<artifactId>c3p0</artifactId>
	<version>0.9.1.2</version>
</dependency>
<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12</version>
</dependency>

1.1.3 创建数据表

create table account(
    id    int primary key auto_increment,
    name  varchar(40),
    money float
)character set utf8 collate utf8_general_ci;

insert into account(name, money)values ('aaa', 1000);
insert into account(name, money)values ('bbb', 1000);
insert into account(name, money)values ('ccc', 1000);

1.1.4 创建实体类

Account.java

package com.spg.domain;

import java.io.Serializable;

/**
 * 账户的实体类
 */
public class Account implements Serializable {

    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

1.1.5 创建持久层代码

AccountDao.java

package com.spg.dao;

import com.spg.domain.Account;

import java.util.List;

/**
 * 账户的持久层接口
 */
public interface AccountDao {

    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 删除
     * @param acccountId
     */
    void deleteAccount(Integer acccountId);
}

AccountDaoImpl.java

package com.spg.dao.impl;

import com.spg.dao.AccountDao;
import com.spg.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.List;

/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl implements AccountDao {

    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    @Override
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer accountId) {
        try{
            return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        try{
            runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        try{
            runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

1.1.6 创建业务层代码

AccountService.java

package com.spg.service;

import com.spg.domain.Account;

import java.util.List;

/**
 * 账户的业务层接口
 */
public interface AccountService {

    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 删除
     * @param acccountId
     */
    void deleteAccount(Integer acccountId);
}

AccountServiceImpl.java

package com.spg.service.impl;

import com.spg.dao.AccountDao;
import com.spg.domain.Account;
import com.spg.service.AccountService;

import java.util.List;

/**
 * 账户的业务层实现类
 */
public class AccountServiceImpl implements AccountService{

    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }
}

1.1.7 创建配置文件bean.xml

<?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.spg.service.impl.AccountServiceImpl">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"/>
    </bean>

    <!--配置Dao对象-->
    <bean id="accountDao" class="com.spg.dao.impl.AccountDaoImpl">
        <!-- 注入QueryRunner -->
        <property name="runner" ref="runner"/>
    </bean>

    <!--配置QueryRunner-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源-->
        <constructor-arg name="ds" ref="dataSource"/>
    </bean>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3307/t117"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>
</beans>

1.1.8 测试

AccountServiceTest .java

package com.spg.test;

import com.spg.domain.Account;
import com.spg.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * 使用Junit单元测试:测试我们的配置
 */

public class AccountServiceTest {

    @Test
    public void testFindAll(){
        // 1.获取容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        // 2.得到业务层对象
        AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
        // 3.执行方法
        List<Account> accounts = accountService.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne(){
        // 1.获取容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        // 2.得到业务层对象
        AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
        // 3.执行方法
        Account account = accountService.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave(){
        // 1.获取容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        // 2.得到业务层对象
        AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
        // 3.执行方法
        Account account = new Account();
        account.setName("Lily");
        account.setMoney(1000f);
        accountService.saveAccount(account);
    }

    @Test
    public void testUpdate(){
        // 1.获取容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        // 2.得到业务层对象
        AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
        // 3.执行方法
        Account account = new Account();
        account.setId(4);
        account.setName("rose");
        account.setMoney(3000f);
        accountService.updateAccount(account);
    }

    @Test
    public void testDelete(){
        // 1.获取容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        // 2.得到业务层对象
        AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
        // 3.执行方法
        accountService.deleteAccount(4);
    }
}

1.2 Spring新注解

1.2.1 @Configuration和@ComponentScan的使用

创建SpringConfiguration.java

package com.spg.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 * Spring中的新注解:
 *  @Configuration:
 *      作用:指定当前类是一个配置类
 *      细节:
 *          当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写
 *  @ComponentScan:
 *      作用:用于通过注解指定spring在创建容器时要扫描的包
 *      属性:
 *          value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包
 *                 我们使用此注解就等同于在XML中配置了:
 *                     <context:component-scan base-package="com.spg"/>
 */
@Configuration
@ComponentScan("com.spg")
public class SpringConfiguration {
    
}

1.2.2 @Bean的使用

修改SpringConfiguration.java

package com.spg.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 *  @Bean:
 *      作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器
 *      属性:
 *          name:用于指定bean的id。当不写时默认值是当前方法的名称
 *      细节:
 *          当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。
 *          查找的方式和Autowired注解的作用是一样的
 *      <!--配置QueryRunner-->
 *      <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
 *          <!--注入数据源-->
 *          <constructor-arg name="ds" ref="dataSource"/>
 *      </bean>
 *      <!-- 配置数据源 -->
 *      <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
 *          <!--连接数据库的必备信息-->
 *          <property name="driverClass" value="com.mysql.jdbc.Driver"/>
 *          <property name="jdbcUrl" value="jdbc:mysql://localhost:3307/t117"/>
 *          <property name="user" value="root"/>
 *          <property name="password" value="root"/>
 *      </bean>
 */
@Configuration
@ComponentScan("com.spg")
public class SpringConfiguration {

    /**
     * 用于创建一个QueryRunner对象
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3307/t117");
            ds.setUser("root");
            ds.setPassword("root");
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

1.2.3 AnnotationConfigApplicationContext的使用

修改AccountServiceTest.java

package com.spg.test;

import com.spg.config.SpringConfiguration;
import com.spg.domain.Account;
import com.spg.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * 使用Junit单元测试:测试我们的配置
 */

public class AccountServiceTest {

    @Test
    public void testFindAll(){
        // 1.获取容器
//        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        // 2.得到业务层对象
        AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
        // 3.执行方法
        List<Account> accounts = accountService.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne(){
        // 1.获取容器
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        // 2.得到业务层对象
        AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
        // 3.执行方法
        Account account = accountService.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave(){
        // 1.获取容器
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        // 2.得到业务层对象
        AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
        // 3.执行方法
        Account account = new Account();
        account.setName("Lily");
        account.setMoney(1000f);
        accountService.saveAccount(account);
    }

    @Test
    public void testUpdate(){
        // 1.获取容器
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        // 2.得到业务层对象
        AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
        // 3.执行方法
        Account account = new Account();
        account.setId(4);
        account.setName("rose");
        account.setMoney(3000f);
        accountService.updateAccount(account);
    }

    @Test
    public void testDelete(){
        // 1.获取容器
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        // 2.得到业务层对象
        AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
        // 3.执行方法
        accountService.deleteAccount(4);
    }

}

创建QueryRunnerTest.java

package com.spg.test;

import com.spg.config.SpringConfiguration;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * 测试QueryRunner是否单例
 */
public class QueryRunnerTest {
    @Test
    public void testQueryRunner(){
        // 1.获取容器
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        // 2.获取QueryRunner对象
        QueryRunner runner = applicationContext.getBean("runner", QueryRunner.class);
        QueryRunner runner1 = applicationContext.getBean("runner", QueryRunner.class);
        System.out.println(runner == runner1); // true 单例
    }
}

运行结果:
在这里插入图片描述
bean.xml文件中是多例的,因此应增添 @Scope("prototype")
修改SpringConfiguration.java

package com.spg.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;

/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 */
@Configuration
@ComponentScan("com.spg")
public class SpringConfiguration {

    /**
     * 用于创建一个QueryRunner对象
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name = "dataSource")
    @Scope("prototype")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3307/t117");
            ds.setUser("root");
            ds.setPassword("root");
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

1.2.4 @Import的使用

创建JdbcConfig.java

package com.spg.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;

/**
 * 和spring连接数据库相关的配置类
 */
//@Configuration
public class JdbcConfig {

    /**
     * 用于创建一个QueryRunner对象
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name = "dataSource")
    @Scope("prototype")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3307/t117");
            ds.setUser("root");
            ds.setPassword("root");
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

修改SpringConfiguration.java

package com.spg.config;

import org.springframework.context.annotation.*;

/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 * Spring中的新注解:
 * @Import:
 *      作用:用于导入其它的配置类
 *      属性:
 *          value:用于指定其他配置类的字节码。
 *              当我们使用@Import的注解之后,有@Import注解的类就是父配置类,而导入的都是子配置类
 */
//@Configuration
@ComponentScan("com.spg")
@Import(JdbcConfig.class)
public class SpringConfiguration {

}

1.2.5 @PropertySource的使用

创建jdbcConfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3307/t117
jdbc.username=root
jdbc.password=root

修改JdbcConfig.java

package com.spg.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;

/**
 * 和spring连接数据库相关的配置类
 */
//@Configuration
public class JdbcConfig {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    /**
     * 用于创建一个QueryRunner对象
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name = "dataSource")
    @Scope("prototype")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

修改SpringConfiguration.java

package com.spg.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;

/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 *  @PropertySource:
 *      作用:用于指定properties文件的位置
 *      属性:
 *          value:指定文件的名称和路径。
 *              关键字:classpath,表示类路径下
 */
//@Configuration
@ComponentScan("com.spg")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {

}

1.2.6 @Qualifier的另一种用法

当有两个数据源时dataSource1、dataSource2,会报错
修改JdbcConfig.java

package com.spg.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;

/**
 * 和spring连接数据库相关的配置类
 */
//@Configuration
public class JdbcConfig {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    /**
     * 用于创建一个QueryRunner对象
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(@Qualifier("dataSource2") DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name = "dataSource2")
    @Scope("prototype")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Bean(name = "dataSource1")
    @Scope("prototype")
    public DataSource createDataSource1(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl("jdbc:mysql://localhost:3307/u3t117");
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

问题就解决了

1.2.7 Spring整合Junit完成

(1)第一步:pom.xml中引入依赖

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-aop</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>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12</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 AccountService accountService  ;
}

代码示例:修改AccountServiceTest.java

package com.spg.test;

import com.spg.config.SpringConfiguration;
import com.spg.domain.Account;
import com.spg.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * 使用Junit单元测试:测试我们的配置
 * Spring整合junit的配置
 *      1、导入spring整合junit的jar(坐标)
 *      2、使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
 *
 *      @Runwith
 *      3、告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置
 *          @ContextConfiguration
 *              locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
 *              classes:指定注解类所在地位置
 *
 * 当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest1 {

    @Autowired
    private AccountService accountService = null;

    @Test
    public void testFindAll() {
        //3.执行方法
        List<Account> accounts = accountService.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne() {
        //3.执行方法
        Account account = accountService.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("test");
        account.setMoney(1000f);
        //3.执行方法
        accountService.saveAccount(account);

    }

    @Test
    public void testUpdate() {
        //3.执行方法
        Account account = accountService.findAccountById(4);
        account.setMoney(3000f);
        accountService.updateAccount(account);
    }

    @Test
    public void testDelete() {
        //3.执行方法
        accountService.deleteAccount(4);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值