Maxon's Blog

Spring 集成 Junit

3

Spring 集成 Junit

原始Junit测试Spring的问题

  • 在测试类中,每个测试方法都有一下两行代码

    Java
    ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
    Service bean = app.getBean(Service.class);
    
  • 这两行代码的作用是获取Spring容器,如果不写的话,会直接提示空指针异常,所以又不能轻易删掉

上述问题解决思路:

  • 让SpringJunit负责Spring容器的创建,但是需要将配置文件的名称告诉他
  • 将需要进行测试的Bean直接在测试类中进行注入

Spring集成Junit步骤

  • 导入Spring集成Junit坐标

  • Xml
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.3.11</version>
    </dependency>
    
  • 使用@Runwith注解替换原来的运行期

    Java
    @RunWith(SpringJUnit4ClassRunner.class)		
    
  • 使用@ContextConfiguration制订配置文件或配置类

    Java
    @ContextConfiguration("classpath:applicationContext.xml")
    
  • 使用@Aurowired注入需要测试的对象

  • Java
    @Autowired
    private DataSource dataSource;
    
  • 创建测试方法进行测试

    Java
    @Test
    public void test1() throws SQLException {
        System.out.println(dataSource.getConnection());
    }