码迷,mamicode.com
首页 > 编程语言 > 详细

Spring与junit测试

时间:2014-09-22 02:42:11      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:junit   spring   

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

这个Spring测试需要的jar包:

     spring-test-3.2.0.RELEASE.jar

2.Spring和Junit的关系图

bubuko.com,布布扣

左边的采用传统的方式,即一般的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")





Spring与junit测试

标签:junit   spring   

原文地址:http://blog.csdn.net/u011662320/article/details/39457971

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!