首页 > 其他 > 详细

Junit问题01 利用 @Autowired 注入失效问题

时间:2018-08-11 15:17:39      阅读:283      评论:0      收藏:0      [点我收藏+]

 

1 利用 @Autowired 注入失效问题 

  1.1 问题描述

    在使用Junit作为测试框架的单元测试中,直接了用@Autowired记性依赖注入时总是注入失败

  1.2 问题原因

    在测试类中没有设定上下文的配置文件信息,指定运行环境为Spring环境

技术分享图片
@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" }) 
View Code

  1.3 问题解决

    在测试类上添加下面两行注解

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})

    技巧01:applicationContext.xml 是一个配置bean的文件

Junit问题01 利用 @Autowired 注入失效问题

原文:https://www.cnblogs.com/NeverCtrl-C/p/9459742.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!