当前位置: 移动技术网 > IT编程>开发语言>Java > Spring之junit测试集成

Spring之junit测试集成

2019年12月08日  | 移动技术网IT编程  | 我要评论

简介

spring提供spring-test-5.2.1.release.jar 可以整合junit。
优势:可以简化测试代码(不需要手动创建上下文,即手动创建spring容器)

使用spring和junit集成的步骤

1.导入jar包

2.创建包com.igeek.test,创建类springtest

通过@runwith注解,使用junit整合spring
通过@contextconfiguration注解,指定spring容器的位置

3.通过@autowired注解,注入需要测试的对象
在这里注意两点:

将测试对象注入到测试用例中

测试用例不需要配置,因为使用测试类运行的时候,会自动启动注解的支持(仅对该测试类启用)

举例说明一下

1.第一种:在applicationcontext.xml中不开启注解扫描

配置文件:

<?xml version="1.0" encoding="utf-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"       
xmlns:context="http://www.springframework.org/schema/context"       xmlns:aop="http://www.springframework.org/schema/aop"       
xsi:schemalocation="http://www.springframework.org/schema/beans        
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context 
https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop 
https://www.springframework.org/schema/aop/spring-aop.xsd">     

    <bean id="userservice" class="com.igeek.service.impl.userserviceimpl"></bean>
</beans>

service层:

public class userserviceimpl implements iuserservice {

    @override    
    public void save() { 
        system.out.println("save...");   
    }
}

测试类:

@runwith(springjunit4classrunner.class)
@contextconfiguration(locations = "classpath:applicationcontext.xml")
public class test01 { 
    @autowired   
    private iuserservice userservice;
    
    @test    
    public void test01(){ 
        userservice.save();   
    }
}

2.第二种:在applicationcontext.xml中开启注解扫描

配置文件:

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"       
xmlns:context="http://www.springframework.org/schema/context"       xmlns:aop="http://www.springframework.org/schema/aop"       
xsi:schemalocation="http://www.springframework.org/schema/beans        
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context 
https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop 
https://www.springframework.org/schema/aop/spring-aop.xsd">  

<!--开启注解扫描-->    
<context:component-scan base-package="com.igeek"></context:component-scan>
</beans>

service层:

@service("userservice")
public class userserviceimpl implements iuserservice {

    @override    
    public void save() { 
        system.out.println("save...");   
    }
}

测试类:

@runwith(springjunit4classrunner.class)
@contextconfiguration(locations = "classpath:applicationcontext.xml")
public class test01 { 
    @autowired   
    private iuserservice userservice;
    
    @test    
    public void test01(){ 
        userservice.save();   
    }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网