spring整合junit

配置步骤:

  1.添加测试坐标

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>

  2.使用@RunWith 注解替换原有运行器(把原有的main方法替换了,替换成 spring 提供的)

    @RunWith(SpringJUnit4ClassRunner.class)
    public class AccountServiceTest {
    }

  3.使用@ContextConfiguration 指定 spring 配置文件的位置

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations= {"classpath:bean.xml"})
    public class AccountServiceTest {
    }

    @ContextConfiguration 注解:
    locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明
    classes 属性:用于指定注解的配置类。当不使用 xml 配置时,需要用此属性指定注解配置类的位置。

  4.使用@Autowired 给测试类中的变量注入数据

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations= {"classpath:bean.xml"})
    public class AccountServiceTest {
      @Autowired
      private AccountService as ;
    }

  注意:当使用 spring 5.x.x 版本的时候,要求 junit 的 jar 包必须是 4.12 及以上。

    

为什么不把测试类配到 xml 中?配到 XML 中能不能用呢?

  答案是肯定的,没问题,可以使用。
那么为什么不采用配置到 xml 中的方式呢?
  第一:当我们在 xml 中配置了一个 bean,spring 加载配置文件创建容器时,就会创建对象。
  第二:测试类只是我们在测试功能时使用,而在项目中它并不参与程序逻辑,也不会解决需求上的问题,
     所以创建完了,并没有使用。那么存在容器中就会造成资源的浪费。
  所以,基于以上两点,我们不应该把测试配置到 xml 文件中。

原文地址:https://www.cnblogs.com/roadlandscape/p/12301997.html