Spring的junit4测试集成

                                 Spring的junit测试集成

Spring提供spring-test-4.2.4.RELEASE.jar 可以整合junit。

优势:可以简化测试代码(不需要手动创建上下文,即手动创建spring容器)

 

使用spring和junit集成

第一步:新建项目导入junit 开发包

第二步:导入spring-test-4.2.4.RELEASE.jar

第三步: 创建包com.igeek.test,创建类SpringTest

通过@RunWith注解,使用junit整合spring

         通过@ContextConfiguration注解,指定spring容器的位置

//目标:测试一下spring的bean的某些功能

@RunWith(SpringJUnit4ClassRunner.class)//junit整合spring的测试//立马开启了spring的注解

@ContextConfiguration(locations="classpath:applicationContext.xml")//加载核心配置文件,自动构建spring容器

public class SpringTest {

    //使用注解注入要测试的bean

    @Autowired

    private HelloService helloService;

   

    @Test

    public void testSayHello(){

       //获取spring容器

//     ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

       //从spring容器中获取bean对象

//     HelloService helloService=(HelloService)applicationContext.getBean("helloService");

       //测试业务功能

       helloService.sayHello();

      

    }

}

上述代码表示:在测试类运行前的初始化的时候,会自动创建ApplicationContext对象

 

第四步: 通过@Autowired注解,注入需要测试的对象

在这里注意2点:

  1. 将测试对象注入到测试用例中
  2. 测试用例不需要配置,或者是,因为使用测试类运行的时候,会自动启动注解的支持。

//使用注解注入要测试的bean 

   @Autowired

    private HelloService helloService;

 

第五步:调用测试方法完成测试 

   @Test

    public void testSayHello(){

       helloService.sayHello();

    }

第六步:在applicationContext.xml中添加:



    

    

    

    

 

你可能感兴趣的:(java)