Spring整合Junit

1、问题分析

1)应用程序的入口:main方法

2)junit单元测试中,没有main方法也能执行

a.junit集成了一个main方法

b.该方法就会判断当前测试类中哪些方法有@Test注解

c.junit就让有@Test注解的方法执行

3)junit不会管是否采用spring框架

a.在执行方法时,junit根本不知道当前是不是使用了spring框架

b.所以也就不会读取配置文件/配置类创建spring核心容器

4)有以上三点可知

a.当测试方法执行时,没有Ioc容器,就算写了Autowired注解,也无法实现注入

2、Spring整合Junit的配置

    1)导入spring整合junit的jar(坐标)

2)使用junit提供的一个注解把原有的main方法替换了,替换成spring提供的@RunWith注解

3)告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置

a.@ContextConfiguration

i.locations:指定xml文件的位置,加上classpath关键字,表示在类路径下

ii.classes:指定注解类所在的位置

    3、示例代码:

  1. /** 
  2.  * 使用Junit单元测试:测试配置 
  3.  * Spring整合Junit的配置 
  4.  *      1、导入spring整合junitjar(坐标) 
  5.  *      2、使用junit提供的一个注解把原有的main方法替换了,替换成spring提供的 
  6.  *          @RunWith 
  7.  *      3、告知spring的运行器,springioc创建是基于xml还是注解的,并且说明位置 
  8.  *          ContextConfiguration 
  9.  *              locations:指定xml文件的位置,加上classpath关键字,表示在类路径下 
  10.  *              classes:指定注解类所在的位置 
  11.  * 使用Spring 5.x版本的时候,要求Junitjar必须是4.12及以上 
  12.  */  
  13. @RunWith(SpringJUnit4ClassRunner.class)  
  14. @ContextConfiguration(classes = SpringConfiguration.class)//使用注解配置  
  15. //@ContextConfiguration(locations = "classpath:bean.xml")//使用xml配置文件  
  16. public class AccountServiceTest {  
  17.   
  18.     @Autowired  
  19.     private IAccountService as;  
  20.   
  21.     @Test  
  22.     public void testFindAll() {  
  23.         //3.执行方法  
  24.         List<Account> accounts = as.findAll();  
  25.         for (Account account : accounts) {  
  26.             System.out.println(account);  
  27.         }  
  28.     }  
  29.   
  30.     @Test  
  31.     public void testFindOne() {  
  32.         //3.执行方法  
  33.         Account account = as.findById(2);  
  34.         System.out.println(account);  
  35.     }  
  36.   
  37.     @Test  
  38.     public void testSave() {  
  39.         //3.执行方法  
  40.         Account account = new Account();  
  41.         account.setName("test anno withoutxml");  
  42.         account.setMoney(12345f);  
  43.         as.save(account);  
  44.     }  
  45.   
  46.     @Test  
  47.     public void testUpdate() {  
  48.         //3.执行方法  
  49.         Account account = as.findById(6);  
  50.         account.setMoney(23456f);  
  51.         as.update(account);  
  52.     }  
  53.   
  54.     @Test  
  55.     public void testDelete() {  
  56.         //3.执行方法  
  57.         as.delete(6);  
  58.     }  
  59. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值