Spring与junit测试

1.我们知道无论在J2SE还是android中都有junit测试,利用junit能够帮助方便测试代码。在之前的博客中我也写了一些J2SE的一些junit测试例子,今天对于Spring中junit小小的讨论一下。

这个Spring测试需要的jar包:

     spring-test-3.2.0.RELEASE.jar

2.Spring和Junit的关系图


左边的采用传统的方式,即一般的J2SE的方式测试代码,这种情况会有些问题:

(1).每一个测试都要启动Spring,

(2).这种情况下,是测试代码管理Spring容器,而与Spring容器管理测试代码想背了。

或许还有其他的情况,因此应该采用右边的方式进行junit测试,同时也正验证了Spring框架图,为啥Test在最下面


3.简单的案例:

package cn.wwh.www.spring.bbb.test;

/**
 *类的作用:
 *
 *
 *@author 一叶扁舟
 *@version 1.0
 *@创建时间: 2014-9-21   下午03:22:26
 */
public class HelloWorld {
	public  void show() {
		System.out.println("Hello World! This is my first Spring!");

	}
}



测试案例:

package cn.wwh.www.spring.bbb.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 *类的作用:测试在Spring中写测试框架
 *
 *
 *@author 一叶扁舟
 *@version 1.0
 *@创建时间: 2014-9-21   下午10:19:41
 */
//表示先启动Spring容器,把junit运行在Spring容器中
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class SpringtestTest {
	
	
	//自动装配Spring容器
	@Autowired
	private BeanFactory factory;

	@Test
	public void testBeanFactory() throws Exception {
		 HelloWorld  world = factory.getBean("helloWorld",HelloWorld.class);
		 world.show();
		
	}
}


SpringtestTest-context.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"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd">
	<bean id="helloWorld" class="cn.wwh.www.spring.bbb.test.HelloWorld"/>
	
</beans>

注意:

(1).@RunWith(SpringJUnit4ClassRunner.class)

     @ContextConfiguration

     @Autowired

     @Test

     这些都是测试标签

(2).@ContextConfiguration去找配置文件,默认从当前路径去找

如果置文件名= 当前测试类名-context.xml,就可以在当前路径找.可以省略如上面的SpringtestTest-context.xml,测试类为:SpringtestTest.java

如果不是按照约定写的,测需要按照加载路径的格式写:

@ContextConfiguration("classpath:cn/wwh/www/spring/bbb/test/SpringtestTest-context.xml")





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值