天天看点

Spring 学习之-原始Junit测试Spring的问题1. 原始Junit测试Spring的问题

1. 原始Junit测试Spring的问题

在测试类中,每个测试方法都有两行代码:
ApplicationContext app = new ClassPathXmlApplicationContext("bean.xml");
IAccountSercice as = app.getBean("accountService",IAccountService.class);
           
这两行代码的作用就是获取容器,如果不写,直接回提示空指针异常。所以不能轻易删掉。
第一行代码:获得应用上下文对象
第二行代码:获取要被测试的对象

上述问题的解决思想

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

Spring集成Junit步骤

  1. 导入Spring集成junit的坐标
  2. 使用@Runwith注解替换原来的运行期
  3. 使用@ContextCondiguration指定配置文件或配置类
  4. 使用@Autowire注入需要测试的对象
  5. 创建测试方法进行测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringJunitTest {
     @Autowired
     private UserService userService;//注入
     
     @Test
    public void test1(){
         userService.save();
    }
}
           
遇到的错误
Caused by: java.lang.IllegalStateException: SpringJUnit4ClassRunner requires JUnit 4.12 or higher
           

表示:由错误提示可知,junit版本低了,需要4.12或更高,“As of Spring Framework 4.3, this class requires JUnit 4.12 or higher”

输出

Service 对象的初始化方法
com.mysql.jdbc.Driver
save running.....
Service 对象的销毁方法
           
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringJunitTest {

@Autowired
private UserService userService;

@Autowired
private DataSource dataSource;

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

}  
           

输出:

Service 对象的初始化方法
com.mysql.jdbc.Driver
save running.....
com.m[email protected]
Service 对象的销毁方法
           

使用全注解方式编写:

相当于告诉它,我现在要的不是配置文件,而是一个配置类,要把这个配置类的字节码告诉他
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(classes = {SpringConfiguration.class})//配置类
public class SpringJunitTest {

@Autowired
private UserService userService;

    @Autowired
    private DataSource dataSource;

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

输出:

com.mysql.jdbc.Driver
save running.....
com.m[email protected]
Service 对象的销毁方法
           

总结:

只需要将环境搭好,就在这个地方注入谁,在这个地方进行环境测试就行