spring之单元测试
上一篇 / 下一篇 2012-06-29 10:20:35 / 个人分类:性能测试
spring可以基于junit3.8、junit4.4、testNG的环境,但是注意基于junit4.4和testNG要在java1.4(包括1.4)以上的版本。
首先环境(一):spring2.5.4、junit3.8、java1.6、eclipse
使用junit3.8有两种测试的方法,两种测试方法分别extends不同的类,我们一个一个来。
第一种方法A:
A方法要求测试的类继承org.springframework.test包中类,我们先来看看这个包的类的继承关系:
AbstractSpringContextTests
|
AbstractSingleSpringContextTests
|
AbstractDependencyInjectionSpringContextTests
|
AbstractTransactionalSpringContextTests
|
AbstractTransactionalDataSourceSpringContextTests
最上面的是父类,接着第二个继承第一个以此类推。
好了我们看看 AbstractSpringContextTests
- /**
- * Map of context keys returned by subclasses of this class, to Spring
- * contexts. This needs to be static, as JUnit tests are destroyed and
- * recreated between running individual test methods.
- */
- private static Map contextKeyToContextMap = new HashMap();
- /**
- * Default constructor for AbstractSpringContextTests.
- */
- public AbstractSpringContextTests() {
- }
- /**
- * Constructor for AbstractSpringContextTests with a JUnit name.
- */
- public AbstractSpringContextTests(String name) {
- super(name);
- }
/** * Map of context keys returned by subclasses of this class, to Spring * contexts. This needs to be static, as JUnit tests are destroyed and * recreated between running individual test methods. */ private static Map contextKeyToContextMap = new HashMap(); /** * Default constructor for AbstractSpringContextTests. */ public AbstractSpringContextTests() { } /** * Constructor for AbstractSpringContextTests with a JUnit name. */ public AbstractSpringContextTests(String name) { super(name); }
- /**
- * Load a new ApplicationContext for the given key.
- * <p>
- * To be implemented by subclasses.
- *
- * @param key the context key
- * @return the corresponding ApplicationContext instance (new)
- */
- protected abstract ConfigurableApplicationContext loadContext(Object key) throws Exception;
/** * Load a new ApplicationContext for the given key. * <p> * To be implemented by subclasses. * * @param key the context key * @return the corresponding ApplicationContext instance (new) */ protected abstract ConfigurableApplicationContext loadContext(Object key) throws Exception;
注意看这个static Map contextKeyToContextMap 这个是用来存放context的缓存区,作用稍后在说,
看下面的这个抽象方法,它的作用是用来loadContext,这方法的实现在它子类AbstractSingleSpringContextTests
中。看AbstractSingleSpringContextTests中的实现:
- /**
- * <p>
- * This implementation assumes a key of type String array and loads a
- * context from the given locations.
- * </p>
- * <p>
- * If you override {@link #contextKey()}, you will typically have to
- * override this method as well, being able to handle the key type that
- * <code>contextKey()</code> returns.
- * </p>
- *
- * @see #getConfigLocations()
- */
- protected ConfigurableApplicationContext loadContext(Object key) throws Exception {
- return loadContextLocations((String[]) key);
- }
- protected ConfigurableApplicationContext loadContextLocations(String[] locations) throws Exception {
- ++this.loadCount;
- if (this.logger.isInfoEnabled()) {
- this.logger.info("Loading context for locations: " + StringUtils.arrayToCommaDelimitedString(locations));
- }
- return createApplicationContext(locations);
- }
- protected ConfigurableApplicationContext createApplicationContext(final String[] locations) {
- GenericApplicationContext context = new GenericApplicationContext();
- customizeBeanFactory(context.getDefaultListableBeanFactory());
- createBeanDefinitionReader(context).loadBeanDefinitions(locations);
- context.refresh();
- return context;
- }
/** * <p> * This implementation assumes a key of type String array and loads a * context from the given locations. * </p> * <p> * If you override {@link #contextKey()}, you will typically have to * override this method as well, being able to handle the key type that * <code>contextKey()</code> returns. * </p> * * @see #getConfigLocations() */ protected ConfigurableApplicationContext loadContext(Object key) throws Exception { return loadContextLocations((String[]) key); } protected ConfigurableApplicationContext loadContextLocations(String[] locations) throws Exception { ++this.loadCount; if (this.logger.isInfoEnabled()) { this.logger.info("Loading context for locations: " + StringUtils.arrayToCommaDelimitedString(locations)); } return createApplicationContext(locations); } protected ConfigurableApplicationContext createApplicationContext(final String[] locations) { GenericApplicationContext context = new GenericApplicationContext(); customizeBeanFactory(context.getDefaultListableBeanFactory()); createBeanDefinitionReader(context).loadBeanDefinitions(locations); context.refresh(); return context; }
可以看到这个方法的实现了加载配置文件的作用,那我们怎么将我们的配置文件给AbstractSingleSpringContextTests
让它加载呢,AbstractSingleSpringContextTests有一个让我们测试类继承的方法String[] getConfigLocations()
- protected String[] getConfigLocations() {
- String[] paths = getConfigPaths();
- String[] locations = new String[paths.length];
- for (int i = 0; i < paths.length; i++) {
- String path = paths[i];
- if (path.startsWith("/")) {
- locations[i] = ResourceUtils.CLASSPATH_URL_PREFIX + path;
- }
- else {
- locations[i] = ResourceUtils.CLASSPATH_URL_PREFIX +
- StringUtils.cleanPath(ClassUtils.classPackageAsResourcePath(getClass()) + "/" + path);
- }
- }
- return locations;
- }
protected String[] getConfigLocations() { String[] paths = getConfigPaths(); String[] locations = new String[paths.length]; for (int i = 0; i < paths.length; i++) { String path = paths[i]; if (path.startsWith("/")) { locations[i] = ResourceUtils.CLASSPATH_URL_PREFIX + path; } else { locations[i] = ResourceUtils.CLASSPATH_URL_PREFIX + StringUtils.cleanPath(ClassUtils.classPackageAsResourcePath(getClass()) + "/" + path); } } return locations; }
在上面所说的loadContext的方法中会调用getConfigLocations()获得配置文件的位置,所以我们在我们测试的类中重写这个方法,这样就覆盖了这个方法。所以我们的测试类应该这样写
- public class TeacherDao2Test extends AbstractSingleSpringContextTests{
- protected String entryYear = "2010";
- protected Long gradeId = 1L;
- protected Long classId = 1L;
- protected Long subjectId = 1L;
- protected Long markId = 1L;
- protected Date toDate = new Date();
- protected Date fromDate;
- protected ApplicationContext app;
- // @Resource
- private GenericManager<AdjustedRateStandard, Long> adjustedRateStandardManager;
- protected TeacherDao2 teacherDao2;
- @Override
- protected String[] getConfigLocations() {
- return new String[] {"classpath:applicationContext-resources.xml",
- "classpath:WEB-INF/applicationContext.xml",
- "classpath:applicationContext-dao.xml"};
- }
- public void testGetQualityReviewResultArrayByDate() throws Exception {
- GenericManager<AdjustedRateStandard, Long> adjustedRateStandardManager = (GenericManager<AdjustedRateStandard, Long>) this.getApplicationContext().getBean("adjustedRateStandardManager");
- List<AdjustedRateStandard> a = adjustedRateStandardManager.getAll();
- for(AdjustedRateStandard ar : a) {
- System.out.println(ar.getId());
- System.out.println(ar.getRate());
- System.out.println(ar.getDescription());
- }
- System.out.println("--------------");
- /* a = adjustedRateDao.getAll();
- for(AdjustedRate ar : a) {
- System.out.println(ar.getAreaRate());
- System.out.println(ar.getSubject().getName());
- }*/
- }
- public void testa() {
- /*System.out.println();
- Double x = 2.0;
- Double y = 3.0;
- Double z = 1.2;
- BigDecimal xb = new BigDecimal(String.valueOf(x));
- BigDecimal yb = new BigDecimal(String.valueOf(y));
- BigDecimal zb = new BigDecimal(String.valueOf(z));
- System.out.println(x*y*z);
- System.out.println(xb.multiply(zb).multiply(yb));
- double d = xb.multiply(zb).multiply(yb).doubleValue();
- System.out.println(d);*/
- int[] a = {3,5,9,7,4,13,15,0,2,20};
- boolean[] b = new boolean[21];
- for(int i=0;i<a.length;i++) {
- b[a[i]] = true;
- }
- for(int i=0;i<b.length;i++) {
- if(b[i]) {
- System.out.print(i+",");
- }
- }
- }
- }
public class TeacherDao2Test extends AbstractSingleSpringContextTests{ protected String entryYear = "2010"; protected Long gradeId = 1L; protected Long classId = 1L; protected Long subjectId = 1L; protected Long markId = 1L; protected Date toDate = new Date(); protected Date fromDate; protected ApplicationContext app; // @Resource private GenericManager<AdjustedRateStandard, Long> adjustedRateStandardManager; protected TeacherDao2 teacherDao2; @Override protected String[] getConfigLocations() { return new String[] {"classpath:applicationContext-resources.xml", "classpath:WEB-INF/applicationContext.xml", "classpath:applicationContext-dao.xml"}; } public void testGetQualityReviewResultArrayByDate() throws Exception { GenericManager<AdjustedRateStandard, Long> adjustedRateStandardManager = (GenericManager<AdjustedRateStandard, Long>) this.getApplicationContext().getBean("adjustedRateStandardManager"); List<AdjustedRateStandard> a = adjustedRateStandardManager.getAll(); for(AdjustedRateStandard ar : a) { System.out.println(ar.getId()); System.out.println(ar.getRate()); System.out.println(ar.getDescription()); } System.out.println("--------------"); /* a = adjustedRateDao.getAll(); for(AdjustedRate ar : a) { System.out.println(ar.getAreaRate()); System.out.println(ar.getSubject().getName()); }*/ } public void testa() { /*System.out.println(); Double x = 2.0; Double y = 3.0; Double z = 1.2; BigDecimal xb = new BigDecimal(String.valueOf(x)); BigDecimal yb = new BigDecimal(String.valueOf(y)); BigDecimal zb = new BigDecimal(String.valueOf(z)); System.out.println(x*y*z); System.out.println(xb.multiply(zb).multiply(yb)); double d = xb.multiply(zb).multiply(yb).doubleValue(); System.out.println(d);*/ int[] a = {3,5,9,7,4,13,15,0,2,20}; boolean[] b = new boolean[21]; for(int i=0;i<a.length;i++) { b[a[i]] = true; } for(int i=0;i<b.length;i++) { if(b[i]) { System.out.print(i+","); } } } }
这样的话测试类体通过getApplicationContext()就可以获得一个AplicationContext的对象,这个对象可以直接用getbean方法获得spring的容器中的对象了。
在AbstractSingleSpringContextTests类中只是简单的加载了容器,当使用AbstractDependencyInjectionSpringContextTests
类(及其子类)载入你的应用上下文时, 它们可以通过Setter注入选择性配置你的测试类实例。你需要做的仅仅是定义实例变量和相应的setter方法。AbstractDependencyInjectionSpringContextTests
将在getConfigLocations()
方法定义的配置文件集中自动查找相应对象,注意它使用的是按类型自动装配,因此如果你有多个bean定义是相同的类型,就不能在这些bean中使用这种方法。 这种情况下,你可以使用继承的applicationContext
实例变量并实现显式的查找(比如), 调用applicationContext.getBean("id")
方法。
如果你不希望在测试案例中使用依赖注入,只要不声明任何public
setter方法就可以简单实现。 作为替代的,你可以扩展AbstractSpringContextTests
- 在org.springframework.test
包中的JUnit 3.8集成测试支持类层次的根 - 它仅仅包含了一些载入Spring上下文的简单方法,而且不在测试fixture中使用依赖注入。
AbstractTransactionalSpringContextTests
类 依赖于应用上下文中定义的PlatformTransactionManager
bean。 名字是无关紧要的,因为使用了按类型自动装配,通常你会扩展其子类AbstractTransactionalDataSourceSpringContextTests
。 这个类也需要在应用上下文中有一个DataSource
bean定义(同样可以是任意名称)。 它创建一个JdbcTemplate
实例变量,可以用来方便的查询和删除选定表的内容(请记住默认情况下事务将被回滚,因而这样做是安全的)。
最后说说context缓存的问题,在每个测试的方法被执行的之前都会去加载一次配置文件,所以在spring第一次加载成功以后会将加载的文件名字为key,加载的得到的context为vlaue存在 contextKeyToContextMap ,这样下载在加载的时候就会先去 contextKeyToContextMap 找看有没有对应的key有的话就直接获得context。在一些少见的会“污染”应用上下文的案例中需要重新载入—— 例如,改变一个bean定义或应用对象的状态—— Spring的测试支持提供了在执行下一个测试前让测试fixture重新载入配置并重建应用上下文的机制。方法就是使用AbstractSingleSpringContextTests类中的setDirty()
方法来让测试fixture在执行下一个测试案例时重新载AbstractAnnotationAwareTransactionalTests
类,这个方法就是将contextKeyToContextMap 里的对应的记录给remove掉。
第二种方法B:
我们也可以使用我们的测试类继承AbstractJUnit38SpringContextTests这个类,这是使用Spring TestContext Framework
框架的核心包括TestContext
和TestContextManager
类以及TestExecutionListener
接口。 每次测试都会创建TestContextManager
。TestContextManager
管理了一个TestContext
, 它负责持有当前测试的上下文。TestContextManager
还负责在测试执行过程中更新TestContext
的状态并代 理到TestExecutionListener
, 它用来监测测试实际的执行(如提供依赖注入、管理事务等等)。其实也就是在TestContextManager有一个TestExecutionListener的list,在每次执行测试方法前后是时候都会遍历这个list并执行对应的prepareTestInstance和beforeTestMethod和afterTestMethod方法。
TestContext
:封装测试执行的上下文,与当前使用的测试框架无关。TestContextManager
:Spring TestContext Framework的主入口点, 负责管理单独的TestContext
并在定义好的执行点上向所有注册的TestExecutionListener
发出事件通知: 测试实例的准备,先于特定的测试框架的前置方法,迟于后置方法。TestExecutionListener
:定义了一个监听器API与TestContextManager
发布的测试执行事件进行交互, 而该监听器就是注册到这个TestContextManager
上的。Spring提供了
TestExecutionListener
的三个实现, 他们都是使用默认值进行配置的(通过@TestExecutionListeners
注解):DependencyInjectionTestExecutionListener
、DirtiesContextTestExecutionListener
及TransactionalTestExecutionListener
, 他们对测试实例提供了依赖注入支持,处理@DirtiesContext
注解,并分别使用默认的回滚语义对测试提供事务支持。
好了,直接上例子:
- @ContextConfiguration(locations = {"classpath:applicationContext-resources.xml",
- "classpath:WEB-INF/applicationContext.xml",
- "classpath:applicationContext-dao.xml"})
- public class TeacherDao2Test extends AbstractJUnit38SpringContextTests {
- protected String entryYear = "2010";
- protected Long gradeId = 1L;
- protected Long classId = 1L;
- protected Long subjectId = 1L;
- protected Long markId = 1L;
- protected Date toDate = new Date();
- protected Date fromDate;
- protected ApplicationContext app;
- @Resource
- private GenericManager<AdjustedRateStandard, Long> adjustedRateStandardManager;
- protected TeacherDao2 teacherDao2;
- public void testGetQualityReviewResultArrayByDate() throws Exception {
- // GenericManager<AdjustedRateStandard, Long> adjustedRateStandardManager = (GenericManager<AdjustedRateStandard, Long>) this.getApplicationContext().getBean("adjustedRateStandardManager");
- Assert.assertNotNull("not null", adjustedRateStandardManager);
- List<AdjustedRateStandard> a = adjustedRateStandardManager.getAll();
- for(AdjustedRateStandard ar : a) {
- System.out.println(ar.getId());
- System.out.println(ar.getRate());
- System.out.println(ar.getDescription());
- }
- System.out.println("--------------");
- /* a = adjustedRateDao.getAll();
- for(AdjustedRate ar : a) {
- System.out.println(ar.getAreaRate());
- System.out.println(ar.getSubject().getName());
- }*/
- }
- public void testa() {
- /*System.out.println();
- Double x = 2.0;
- Double y = 3.0;
- Double z = 1.2;
- BigDecimal xb = new BigDecimal(String.valueOf(x));
- BigDecimal yb = new BigDecimal(String.valueOf(y));
- BigDecimal zb = new BigDecimal(String.valueOf(z));
- System.out.println(x*y*z);
- System.out.println(xb.multiply(zb).multiply(yb));
- double d = xb.multiply(zb).multiply(yb).doubleValue();
- System.out.println(d);*/
- int[] a = {3,5,9,7,4,13,15,0,2,20};
- boolean[] b = new boolean[21];
- for(int i=0;i<a.length;i++) {
- b[a[i]] = true;
- }
- for(int i=0;i<b.length;i++) {
- if(b[i]) {
- System.out.print(i+",");
- }
- }
- }
- }
@ContextConfiguration(locations = {"classpath:applicationContext-resources.xml", "classpath:WEB-INF/applicationContext.xml", "classpath:applicationContext-dao.xml"}) public class TeacherDao2Test extends AbstractJUnit38SpringContextTests { protected String entryYear = "2010"; protected Long gradeId = 1L; protected Long classId = 1L; protected Long subjectId = 1L; protected Long markId = 1L; protected Date toDate = new Date(); protected Date fromDate; protected ApplicationContext app; @Resource private GenericManager<AdjustedRateStandard, Long> adjustedRateStandardManager; protected TeacherDao2 teacherDao2; public void testGetQualityReviewResultArrayByDate() throws Exception { // GenericManager<AdjustedRateStandard, Long> adjustedRateStandardManager = (GenericManager<AdjustedRateStandard, Long>) this.getApplicationContext().getBean("adjustedRateStandardManager"); Assert.assertNotNull("not null", adjustedRateStandardManager); List<AdjustedRateStandard> a = adjustedRateStandardManager.getAll(); for(AdjustedRateStandard ar : a) { System.out.println(ar.getId()); System.out.println(ar.getRate()); System.out.println(ar.getDescription()); } System.out.println("--------------"); /* a = adjustedRateDao.getAll(); for(AdjustedRate ar : a) { System.out.println(ar.getAreaRate()); System.out.println(ar.getSubject().getName()); }*/ } public void testa() { /*System.out.println(); Double x = 2.0; Double y = 3.0; Double z = 1.2; BigDecimal xb = new BigDecimal(String.valueOf(x)); BigDecimal yb = new BigDecimal(String.valueOf(y)); BigDecimal zb = new BigDecimal(String.valueOf(z)); System.out.println(x*y*z); System.out.println(xb.multiply(zb).multiply(yb)); double d = xb.multiply(zb).multiply(yb).doubleValue(); System.out.println(d);*/ int[] a = {3,5,9,7,4,13,15,0,2,20}; boolean[] b = new boolean[21]; for(int i=0;i<a.length;i++) { b[a[i]] = true; } for(int i=0;i<b.length;i++) { if(b[i]) { System.out.print(i+","); } } } }
注意,这次我使用了注解@Resource来让spring来自己帮我进行注入,在前面一种方法使用@Resource不行,当然也可以AbstractJUnit38SpringContextTests 的protected ApplicationContext applicationContext来自己在spring中取得。
注意在类的定义处使用@ContextConfiguration注解来把配置文件的位子传递给测试类,@ContextConfiguration总共有3个配置的属性,其他两个是boolean类型inheritLocations以表明是否继承父类的locations和loader表示使用自己的context加载器。
这种方法上下文缓存的处理和第一种方法一样。但是与上面不同的是使用@DirtiesContext这个注解来表示重新加载,使用@DirtiesContext注解的前提是在TestExecutionListeners中加入DirtiesContextTestExecutionListener,而我们的AbstractJUnit38SpringContextTests 中已经设置了DirtiesContextTestExecutionListener,看:
- @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class})
- public abstract class AbstractJUnit38SpringContextTests extends TestCase implements ApplicationContextAware {
- private static int disabledTestCount = 0;
- /**
- * Return the number of tests disabled in this environment.
- */
- public static int getDisabledTestCount() {
- return disabledTestCount;
- }
- ...
- }
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class}) public abstract class AbstractJUnit38SpringContextTests extends TestCase implements ApplicationContextAware { private static int disabledTestCount = 0; /** * Return the number of tests disabled in this environment. */ public static int getDisabledTestCount() { return disabledTestCount; } ... }
事务管理:
对事务的支持可以通过在TestExecutionListeners加入TransactionalTestExecutionListener,同时在类或方法上加上@Transactional就可以支持事务了,在对AbstractJUnit38SpringContextTests类进行扩展了事务和SimpleJdbcTemplate的子类AbstractTransactionalJUnit38SpringContextTests.class是这样配置的。
- @TestExecutionListeners({TransactionalTestExecutionListener.class})
- @Transactional
- public abstract class AbstractTransactionalJUnit38SpringContextTests extends AbstractJUnit38SpringContextTests {
- /**
- * The SimpleJdbcTemplate that this base class manages, available to subclasses.
- */
- protected SimpleJdbcTemplate simpleJdbcTemplate;
- private String sqlScriptEncoding;
- /**
- * Constructs a new AbstractTransactionalJUnit38SpringContextTests instance.
- */
- public AbstractTransactionalJUnit38SpringContextTests() {
- super();
- }
- }
@TestExecutionListeners({TransactionalTestExecutionListener.class}) @Transactional public abstract class AbstractTransactionalJUnit38SpringContextTests extends AbstractJUnit38SpringContextTests { /** * The SimpleJdbcTemplate that this base class manages, available to subclasses. */ protected SimpleJdbcTemplate simpleJdbcTemplate; private String sqlScriptEncoding; /** * Constructs a new AbstractTransactionalJUnit38SpringContextTests instance. */ public AbstractTransactionalJUnit38SpringContextTests() { super(); } }
所以我们可以使测试类继承这个类AbstractTransactionalJUnit38SpringContextTests
下面环境改变: spring2.5.4、junit4.4、java1.6、eclipse
同样的使用了Spring TestContext Framework,Spring TestContext Framework通过一个可定制的运行器提供了与JUnit 4.4的完全集成。 通过使用@Runwith(SpringJUnit4ClassRunner.class)
来注解测试类,开发者可以实现标准的JUnit 4.4单元和集成测试, 同时还能获得TestContext框架的好处,上例子
- @RunWith(SpringJUnit4ClassRunner.class)
- @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class})
- public abstract class AbstractJUnit4SpringContextTests implements ApplicationContextAware {
- /**
- * Logger available to subclasses.
- */
- protected final Log logger = LogFactory.getLog(getClass());
- /**
- * The {@link ApplicationContext} that was injected into this test instance
- * via {@link #setApplicationContext(ApplicationContext)}.
- */
- protected ApplicationContext applicationContext;
- /**
- * Set the {@link ApplicationContext} to be used by this test instance,
- * provided via {@link ApplicationContextAware} semantics.
- */
- public final void setApplicationContext(final ApplicationContext applicationContext) {
- this.applicationContext = applicationContext;
- }
TAG:
标题搜索
日历
|
|||||||||
日 | 一 | 二 | 三 | 四 | 五 | 六 | |||
1 | 2 | 3 | 4 | ||||||
5 | 6 | 7 | 8 | 9 | 10 | 11 | |||
12 | 13 | 14 | 15 | 16 | 17 | 18 | |||
19 | 20 | 21 | 22 | 23 | 24 | 25 | |||
26 | 27 | 28 | 29 | 30 | 31 |
我的存档
数据统计
- 访问量: 17199
- 日志数: 24
- 书签数: 1
- 建立时间: 2012-05-28
- 更新时间: 2013-06-05