9.spring和junit的整合(注解版)

1.看图

2.实体类Account

package com.itheima.domin;

public class Account{
    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;
    }

    /*重写toString方法*/

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

3.业务层接口IAccountService:

package com.itheima.service;

import com.itheima.domin.Account;

import java.util.List;
/*业务层描述功能*/
public interface IAccountService {

    /*找到全部*/
    List<Account> findAllAccount();
    /*找到一个*/
    Account findAccountById(Integer accountId);
    /*保存全部*/
    void  saveAccount(Account account);
    /*更新一条*/
    void updateAccount(Account account);
    /*删除一个*/
    void deleteAccount(Integer accountId);
}

4.业务层实现类:AccountServiceImp

package com.itheima.service.Imp;

import com.itheima.dao.IAccountDao;
import com.itheima.domin.Account;
import com.itheima.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service("accountService")
public class AccountServiceImp implements IAccountService {
    @Autowired
    private IAccountDao 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);
    }
}

5.持久层接口IAccountDao

package com.itheima.dao;

import com.itheima.domin.Account;

import java.util.List;

public interface IAccountDao {

    /*找到全部*/
    List<Account> findAllAccount();
    /*找到一个*/
    Account findAccountById(Integer accountId);
    /*保存全部*/
    void  saveAccount(Account account);
    /*更新一条*/
    void updateAccount(Account account);
    /*删除一个*/
    void deleteAccount(Integer accountId);
}

6.持久层实现类AccountDaoImp

package com.itheima.dao.Imp;

import com.itheima.dao.IAccountDao;
import com.itheima.domin.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository("accountDao")
public class AccountDaoImp implements IAccountDao {
    @Autowired
    private QueryRunner runner;
    /*这里使用Autowired就不会使用set方法注入*/

    @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)value(?,?)",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);
        }
    }
}

7.配置类ConfigurationTest:

package com.itheima.config;


import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
/*全局声明:我是大模块*/
@Configuration
/*扫描包*/
@ComponentScan("com.itheima")
/*引入小模块*/
@Import(JdbcConfig.class)
/*资源配置路径*/
@PropertySource("classpath:jdbcConfig.properties")
public class ConfigurationTest {

}

8.数据源配置类(小模块)JdbcConfig:

package com.itheima.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;

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;

    /*bean的id=runner*/
    @Bean(name="runner")/*用于把当前方法的返回值作为bean对象存入spring的ioc容器中*/
    /*对象为多例因为用到了很多操作,单例满足不了*/
    @Scope("prototype")/*默认单例,改变为多例*/
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner (dataSource);
    }
    @Bean(name="dataSource")
    public DataSource createDataSource(){
        try{
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass(driver);
            dataSource.setJdbcUrl(url);
            dataSource.setUser(username);
            dataSource.setPassword(password);
            /*将值返回*/
            return dataSource;
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }
    /*如果不是分模块,还是比较麻烦的,一般使用两种方式组合*/

}

9.配置文件jdbcConfig.properties:

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/eesy
jdbc.username = root
jdbc.password = 123456

10.测试TestCode:

package com.itheima;

import com.itheima.config.ConfigurationTest;
import com.itheima.domin.Account;
import com.itheima.service.IAccountService;
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;

/*改为spring管理的*/
@RunWith(SpringJUnit4ClassRunner.class)
/*说明位置*/
@ContextConfiguration(classes = ConfigurationTest.class)
public class TestCode {
    /*这样就可以使用spring方式注入了*/
    @Autowired
    private IAccountService as;

    @Test
    public void findAllAccount() {
        /*ApplicationContext ac = new AnnotationConfigApplicationContext(ConfigurationTest.class);
        IAccountService as = ac.getBean("accountService",IAccountService.class);*/
        List<Account> accounts = as.findAllAccount();
        for (Account acc : accounts){
            System.out.println(acc);
        }

    }
    /*以下还有好多操作,我就不一一列出*/
}
/*
* ApplicationContext ac = new AnnotationConfigApplicationContext(ConfigurationTest.class);
        IAccountService as = (IAccountService) ac.getBean("accountService");
  代码重复出现的问题:
  *         1.应用程序的入口
  *             main方法
  *         2.junit单元测试中,没有main方法也能执行
  *             junit集成了一个main方法
  *             该方法就会判断当前测试类中哪些方法有@Test注解
  *             junit就会让有Test注解的方法执行
  *         3. junit不会管我们是否采用spring框架
  *             在执行测试方法时,junit根本不知道是不是使用了spring框架
  *             所以也就不会为我们读取配置文件/配置类创建spring核心容器
  *         4.由以上三点可知
  *             当测试方法执行时,没有Ioc容器,就算写了Autowired注解,也无法实现注入
  *
  * 解决办法:想一想新的依赖和注解方法
  *         也就是说:使用spring整合junit的配置
  *             1.导入spring整合junit的jar坐标
  *             2. 使用junit提供的一个注解把原有的main方法替换了,替换成提供的
  *                     @RunWith
  *             3.告知spring的运行器,spring和ioc创建的是基于xml还时注解的,并且说明位置
  *                     @ContextConfiguration
  *                         Location:指定xml文件的位置,加上classpath关键c字,表示在类路径下
  *                         lasses:指定注解类所在的位置
  *             4.如果运行不成功,请更新依赖版本(junit)
  *
*
*
*
* */

@RunWith

@RunWith就是一个运行器

@RunWith(JUnit4.class)就是指用JUnit4来运行

@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境,

@RunWith(Suite.class)的话就是一套测试集合,

@ContextConfiguration Spring整合JUnit4测试时,使用注解引入多个配置文件 

单个文件 

@ContextConfiguration(Locations="classpath:applicationContext.xml")   
@ContextConfiguration(classes = SimpleConfiguration.class) 

多个文件时,可用{}

@ContextConfiguration(locations = { "classpath:spring1.xml", "classpath:spring2.xml" }) 

结论:基于spring环境,那么就可以实现spring注入

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值