spring测试主要简化的是我们的测试代码。
准备工作 注解测试
1.导入测试jar包,
spring-test-xxx.jar
2.导入注解需要的jar包
spring-aop-xxx.jar
3.导入spring需要的jar包
4个基本jar包,加上日志包
2.编写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" 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"> <!-- bean definitions here -->
<!--cn 是src下的子包,也是src下其它所有包的父包-->
<context:component-scan base-package="cn" />
</beans>
3.创建一个功能类 Cat
//在猫类上加IOC注解注解
@Component(value="c") //其实不是很推荐注解使用Component,虽然可以使用,但可能以后会被 @Controller @service @repository代替,
public class Cat{
public void eat(){
System.out.println("猫在吃");
}
}
4.创建一个测试类
//基本是固定写法
@ContextConfiguration("classpath:applicationContext.xml") //告诉spring的测试环境,xml在哪个位置
@RunWith(SpringJUnit4ClassRunner.class) //这个类是spring自己写的,扩展了junit的运行环境。 在里面还兼备了创建工厂的逻辑
public class Demo(){
//使用注解获取对象
@Resource(name="c") //c 就是猫类注解的value值
private Cat cat;
public void Test_01(){
cat.eat();
}
}
运行结果如下
控制台打印 : 猫在吃
注意: 测试类中的注解不用打开扫描开关。 那个扫描开关仅仅是针对IOC + DI (针对三层中的类)