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. 测试用例不需要配置<context:annotion-config/>,或者是<context:component-scan base-package="com.igeek"/>,因为使用测试类运行的时候,会自动启动注解的支持。

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

   @Autowired

    private HelloService helloService;

 

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

   @Test

    public void testSayHello(){

       helloService.sayHello();

    }

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

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:p="http://www.springframework.org/schema/p"

       xmlns:context="http://www.springframework.org/schema/context"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

                        http://www.springframework.org/schema/beans/spring-beans.xsd

                        http://www.springframework.org/schema/context

                        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 开启组件扫描 -->

    <context:component-scan base-package="com.igeek.ioc"/>

    <!-- 创建Service -->

    <bean id="helloService" class="com.igeek.test.HelloService"></bean>

</beans>

猜你喜欢

转载自blog.csdn.net/qq_15204179/article/details/82975127