Sping中使用Junit进行测试

分析:

1、应用程序的入口
  main方法
2、junit单元测试中,没有main方法也能执行
  junit集成了一个main方法
  该方法就会判断当前测试类中哪些方法有 @Test注解
  junit就让有Test注解的方法执行
3、junit不会管我们是否采用spring框架
  在执行测试方法时,junit根本不知道我们是不是使用了spring框架
  所以也就不会为我们读取配置文件/配置类创建spring核心容器
4、由以上三点可知
  当测试方法执行时,没有Ioc容器,就算写了Autowired注解,也无法实现注入

junit给我们暴露了一个注解,可以让我们替换掉它的运行器

这时,我们需要依靠spring框架,因为它提供了一个运行器,可以读取配置文件(或注解)来创建容器。

我们只需要告诉它配置文件在哪就行了。

pom.xml中添加依赖

 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.6.RELEASE</version>
            <scope>provided</scope>  
</dependency>
<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
</dependency>
<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>test</scope>
</dependency>    

/**
* 使用Junit单元测试:测试我们的配置
* Spring整合junit的配置
* 1、导入spring整合junit的jar(坐标)
* 2、使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
* @Runwith
* 3、告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置
* @ContextConfiguration
* locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
* classes:指定注解类所在地位置
*
* 当我们使用 spring 5.x 版本的时候, 要求junit的jar必须是 4.12 及以上
*/
//@RunWith就是一个运行器  
//@RunWith(JUnit4.class)就是指用JUnit4来运行 
//@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境 
//@RunWith(Suite.class)的话就是一套测试集合 
@RunWith(SpringJUnit4ClassRunner.class
) @ContextConfiguration(locations = {"classpath:bean.xml"})//加载配置文件 public class AccountServiceTest { @Autowired private IAccountService as; @Test public void testFindOne() { //3.执行方法 //ApplicationContext ac= new ClassPathXmlApplicationContext ("bean.xml"); // as=ac.getBean ("accountService",IAccountService.class); Account account = as.findAccountById(1); System.out.println(account); } }

 

原文地址:https://www.cnblogs.com/mkl7/p/10685698.html