在测试的时候 我们还是需要获取ioc容器 然后在容器里获取对象服务类对象 而不能直接从容器里获取对象
我们需要整合junit 就能在测试类里直接获取ioc里的任何对象
首先要导入整合包和junit包
然后在测试类上面写@RunWith(SpringJUnit4ClassRunner.class)
在测试类上面写@ContextConfiguration(classes ={SpringConfig.class} ) 找到容器
@RunWith(SpringJUnit4ClassRunner.class)//替换JUnit4运行器(固定写法)//@ContextConfiguration(value = {"classpath:a.xml","classpath:b.xml"})//加载xml构建ioc容器@ContextConfiguration(classes ={SpringConfig.class} )//通过配置类构建IOC容器public class SpringTest {@Autowiredprivate AccountService accountService;/*** 存在的问题:* 关注点分离:* 当前在进行测试时,我们可能仅仅需要从测试某个服务的执行是否ok* 但是为了执行对应的代码,还需要引入很多我们不需要关注的代码,比如:* ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);* AccountService accountService = ctx.getBean(AccountService.class);* 如果我们想测试什么bean,就直接注入什么bean,那该多好!*/@Testpublic void test01(){// ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);// AccountService accountService = ctx.getBean(AccountService.class);//不用再新建上下文 通过名字获取对象 而是直接注入此类型的对象Account ac = accountService.findById(1);System.out.println(ac);}}
