##问题:
在Junit测试时,在将通用的bean注入提到方法外面形成全局变量时,在运行测试类代码时,会无法注入bean对象。
在Junit单元测试中,没有main方法也能执行,其实是因为Junit集成了一个main方法,该方法会判断当前测试类哪些方法使用了@Test注解,Junit会让有注解的方法执行,但是Junit不会探测是否使用了Spring框架,在执行方法时也不会读取配置文件创建Spring核心容器,所以在Junit中没有没有ioc容器就算写了Autowired注解,bean对象也没办法注入。
##方法:Spring整合Junit的配置
1.导入spring整合junit的配置
2.使用junit提供的注解把原有的runner方法替换为Spring提供的@Runwith
3.告知Spring运行器,spring和IOC创建是基于注解的还是xml配置的,描述文件位置。
4.@ContextConfiguration
locations:指定xml文件的位置,加上classpath关键字,标识在类路径下
classes:指定注解类所在的地址
注:当使用spring5.x版本的时候,要求junit的版本必须是4.12及以上
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = "classpath:applicationContext.xml")
@ContextConfiguration(classes = Car.class)
public class SpringTest {
@Autowired
private Car car;
@Test
public void testFindAll(){
car.produce();
System.out.println("收拾收拾");
}