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>

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_无往而不胜_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值