springboot测试用例注入失败问题

发表于:2022-9-09 09:33

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:茫无所知    来源:博客园

  单元测试用例模板
  @RunWith(SpringRunner.class)
  //@SpringBootTest(classes = PersonConfig.class)
  @ContextConfiguration(classes = PersonConfig.class)
  public class Test {
      @Resource
      private PersonEventService personEventService;
      @Test
      public void test() {
  //        ApplicationContext context = new AnnotationConfigApplicationContext(PersonEventService.class);
  //        PersonEventService personEventService = context.getBean(PersonEventService.class);
          System.out.println(personEventService);
          personEventService.registerUser("userName222");
      }
  }
  @RunWith注解
  解释:
  在正常情况下测试类是需要@RunWith的,作用是告诉java你这个类通过用什么运行环境运行,例如启动和创建spring的应用上下文。否则你需要为此在启动时写一堆的环境配置代码。你在IDEA里去掉@RunWith仍然能跑是因为在IDEA里识别为一个JUNIT的运行环境,相当于就是一个自识别的RUNWITH环境配置。但在其他IDE里并没有,所以尽量加上该注解。
  @ContextConfiguration注解
  解释:
  有两种使用方式:
  1.@ContextConfiguration(locations={"classpath*:/spring1.xml","classpath*:/spring2.xml"})
  指定xml配置文件。
  2.@ContextConfiguration(classes = PersonConfig.class)
  指定java配置类。
  XML方式:
  <?xml version="1.0" encoding="UTF-8"?>
  <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans  
      http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
      http://www.springframework.org/schema/context  
      http://www.springframework.org/schema/context/spring-context-3.1.xsd  >
      <!-- 自动扫描该包 -->
      <context:component-scan base-package="com" />
  </beans>
  这个XML文件通过<context:component-scan base-package="com" />标签将com包下的bean全都自动扫描进来。
  @ContextConfiguration括号里的locations = {"classpath*:/*.xml"}就表示将class路径里的所有.xml文件都包括进来,那么刚刚创建的那么XML文件就会包括进来,那么里面自动扫描的bean就都可以拿到了,此时就可以在测试类中使用@Autowired注解来获取之前自动扫描包下的所有bean
  classpath和classpath*区别:
  ·classpath:只会到你的class路径中查找找文件。
  · classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找。
  JAVA配置类:
  /**
   * 配置文件java
   */
  @Configuration
  @ComponentScan("com.xxx.xxx.controller.eventtest")
  public class PersonEventConfig {
  }
  如果使用Java的方式就会很简单了,我们就不用写XML那么繁琐的文件了,我们可以创建一个Java类来代替XML文件,只需要在这个类上面加上@Configuration注解,然后再加上@ComponentScan注解就开启了自动扫描,如果注解没有写括号里面的东西,@ComponentScan默认会扫描与配置类相同的包。
  相较于XML,是不是很酷炫,这也是官方提倡的方式。
  本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号