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

 

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的文件

    技巧02:juni框架的版本至少是4.12

posted @ 2018-08-11 14:43  寻渝记  阅读(2870)  评论(0编辑  收藏  举报