lsekfe 发表于 2022-9-9 14:36:13

如何避免springboot测试用例注入失败?

 单元测试用例模板
@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,是不是很酷炫,这也是官方提倡的方式。



页: [1]
查看完整版本: 如何避免springboot测试用例注入失败?