Merge branch '3.2.x' into master

Conflicts:
	gradle.properties
	spring-beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java
	spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheManagerFactoryBean.java
	spring-core/src/main/java/org/springframework/core/convert/support/StringToEnumConverterFactory.java
	spring-core/src/main/java/org/springframework/core/env/ReadOnlySystemAttributesMap.java
	spring-jdbc/src/main/java/org/springframework/jdbc/datasource/LazyConnectionDataSourceProxy.java
	spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/AbstractLobHandler.java
	spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpRequestWrapper.java
	spring-web/src/main/java/org/springframework/http/client/SimpleBufferingClientHttpRequest.java
	spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java
	spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java
This commit is contained in:
Chris Beams
2013-03-04 15:41:15 +01:00
1450 changed files with 17678 additions and 42998 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -196,7 +196,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana
* for example, you could specify the same JNDI DataSource for both.
* <p>If the SessionFactory was configured with LocalDataSourceConnectionProvider,
* i.e. by Spring's LocalSessionFactoryBean with a specified "dataSource",
* the DataSource will be auto-detected: You can still explictly specify the
* the DataSource will be auto-detected: You can still explicitly specify the
* DataSource, but you don't need to in this case.
* <p>A transactional JDBC Connection for this DataSource will be provided to
* application code accessing this DataSource directly via DataSourceUtils
@@ -527,7 +527,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana
}
if (definition.isReadOnly() && txObject.isNewSession()) {
// Just set to NEVER in case of a new Session for this transaction.
// Just set to MANUAL in case of a new Session for this transaction.
session.setFlushMode(FlushMode.MANUAL);
}
@@ -779,7 +779,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana
* from the {@code org.springframework.dao} hierarchy.
* <p>Will automatically apply a specified SQLExceptionTranslator to a
* Hibernate JDBCException, else rely on Hibernate's default translation.
* @param ex HibernateException that occured
* @param ex HibernateException that occurred
* @return a corresponding DataAccessException
* @see SessionFactoryUtils#convertHibernateAccessException
* @see #setJdbcExceptionTranslator
@@ -798,7 +798,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana
* Convert the given Hibernate JDBCException to an appropriate exception
* from the {@code org.springframework.dao} hierarchy, using the
* given SQLExceptionTranslator.
* @param ex Hibernate JDBCException that occured
* @param ex Hibernate JDBCException that occurred
* @param translator the SQLExceptionTranslator to use
* @return a corresponding DataAccessException
*/
@@ -887,6 +887,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana
(hasConnectionHolder() && getConnectionHolder().isRollbackOnly());
}
@Override
public void flush() {
try {
this.sessionHolder.getSession().flush();

View File

@@ -30,7 +30,10 @@ import org.hibernate.cache.CacheProvider;
* @author Juergen Hoeller
* @since 2.5.1
* @see LocalSessionFactoryBean#setCacheProvider
* @deprecated as of Spring 3.0, following Hibernate 3.3's deprecation
* of the CacheProvider SPI
*/
@Deprecated
public class LocalCacheProviderProxy implements CacheProvider {
private final CacheProvider cacheProvider;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -621,7 +621,7 @@ public abstract class SessionFactoryUtils {
/**
* Convert the given HibernateException to an appropriate exception
* from the {@code org.springframework.dao} hierarchy.
* @param ex HibernateException that occured
* @param ex HibernateException that occurred
* @return the corresponding DataAccessException instance
* @see HibernateAccessor#convertHibernateAccessException
* @see HibernateTransactionManager#convertHibernateAccessException

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -79,6 +79,8 @@ public class AnnotationSessionFactoryBean extends LocalSessionFactoryBean implem
private static final String RESOURCE_PATTERN = "/**/*.class";
private static final String PACKAGE_INFO_SUFFIX = ".package-info";
private Class[] annotatedClasses;
@@ -101,7 +103,7 @@ public class AnnotationSessionFactoryBean extends LocalSessionFactoryBean implem
@Override
public void setConfigurationClass(Class configurationClass) {
public void setConfigurationClass(Class<?> configurationClass) {
if (configurationClass == null || !AnnotationConfiguration.class.isAssignableFrom(configurationClass)) {
throw new IllegalArgumentException(
"AnnotationSessionFactoryBean only supports AnnotationConfiguration or subclasses");
@@ -191,9 +193,12 @@ public class AnnotationSessionFactoryBean extends LocalSessionFactoryBean implem
if (resource.isReadable()) {
MetadataReader reader = readerFactory.getMetadataReader(resource);
String className = reader.getClassMetadata().getClassName();
if (matchesFilter(reader, readerFactory)) {
if (matchesEntityTypeFilter(reader, readerFactory)) {
config.addAnnotatedClass(this.resourcePatternResolver.getClassLoader().loadClass(className));
}
else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
config.addPackage(className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
}
}
}
}
@@ -211,7 +216,7 @@ public class AnnotationSessionFactoryBean extends LocalSessionFactoryBean implem
* Check whether any of the configured entity type filters matches
* the current class descriptor contained in the metadata reader.
*/
private boolean matchesFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException {
private boolean matchesEntityTypeFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException {
if (this.entityTypeFilters != null) {
for (TypeFilter filter : this.entityTypeFilters) {
if (filter.match(reader, readerFactory)) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@ package org.springframework.orm.jdo;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import javax.jdo.Constants;
import javax.jdo.JDOException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
@@ -32,7 +33,6 @@ import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.jdbc.datasource.ConnectionHandle;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.jdbc.support.SQLExceptionTranslator;
import org.springframework.transaction.InvalidIsolationLevelException;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.util.ClassUtils;
@@ -40,13 +40,13 @@ import org.springframework.util.ReflectionUtils;
/**
* Default implementation of the {@link JdoDialect} interface.
* Updated to build on JDO 2.0 or higher, as of Spring 2.5.
* Requires JDO 2.0; explicitly supports JDO API features up until 3.0.
* Used as default dialect by {@link JdoAccessor} and {@link JdoTransactionManager}.
*
* <p>Simply begins a standard JDO transaction in {@code beginTransaction}.
* Returns a handle for a JDO2 DataStoreConnection on {@code getJdbcConnection}.
* Calls the corresponding JDO2 PersistenceManager operation on {@code flush}
* Ignores a given query timeout in {@code applyQueryTimeout}.
* Translates {@code applyQueryTimeout} to JDO 3.0's {@code setTimeoutMillis}.
* Uses a Spring SQLExceptionTranslator for exception translation, if applicable.
*
* <p>Note that, even with JDO2, vendor-specific subclasses are still necessary
@@ -122,24 +122,49 @@ public class DefaultJdoDialect implements JdoDialect, PersistenceExceptionTransl
//-------------------------------------------------------------------------
/**
* This implementation invokes the standard JDO {@code Transaction.begin}
* method. Throws an InvalidIsolationLevelException if a non-default isolation
* level is set.
* This implementation invokes the standard JDO {@link Transaction#begin()}
* method and also {@link Transaction#setIsolationLevel(String)} if necessary.
* @see javax.jdo.Transaction#begin
* @see org.springframework.transaction.InvalidIsolationLevelException
*/
public Object beginTransaction(Transaction transaction, TransactionDefinition definition)
throws JDOException, SQLException, TransactionException {
if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
throw new InvalidIsolationLevelException(
"Standard JDO does not support custom isolation levels: " +
"use a special JdoDialect implementation for your JDO provider");
String jdoIsolationLevel = getJdoIsolationLevel(definition);
if (jdoIsolationLevel != null) {
transaction.setIsolationLevel(jdoIsolationLevel);
}
transaction.begin();
return null;
}
/**
* Determine the JDO isolation level String to use for the given
* Spring transaction definition.
* @param definition the Spring transaction definition
* @return the corresponding JDO isolation level String, or {@code null}
* to indicate that no isolation level should be set explicitly
* @see Transaction#setIsolationLevel(String)
* @see Constants#TX_SERIALIZABLE
* @see Constants#TX_REPEATABLE_READ
* @see Constants#TX_READ_COMMITTED
* @see Constants#TX_READ_UNCOMMITTED
*/
protected String getJdoIsolationLevel(TransactionDefinition definition) {
switch (definition.getIsolationLevel()) {
case TransactionDefinition.ISOLATION_SERIALIZABLE:
return Constants.TX_SERIALIZABLE;
case TransactionDefinition.ISOLATION_REPEATABLE_READ:
return Constants.TX_REPEATABLE_READ;
case TransactionDefinition.ISOLATION_READ_COMMITTED:
return Constants.TX_READ_COMMITTED;
case TransactionDefinition.ISOLATION_READ_UNCOMMITTED:
return Constants.TX_READ_UNCOMMITTED;
default:
return null;
}
}
/**
* This implementation does nothing, as the default beginTransaction implementation
* does not require any cleanup.

View File

@@ -481,7 +481,6 @@ public class JdoTemplate extends JdoAccessor implements JdoOperations {
public Collection find(final String queryString) throws DataAccessException {
return execute(new JdoCallback<Collection>() {
@SuppressWarnings("unchecked")
public Collection doInJdo(PersistenceManager pm) throws JDOException {
Query query = pm.newQuery(queryString);
prepareQuery(query);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -76,10 +76,12 @@ public abstract class EntityManagerFactoryUtils {
* Find an EntityManagerFactory with the given name in the given
* Spring application context (represented as ListableBeanFactory).
* <p>The specified unit name will be matched against the configured
* peristence unit, provided that a discovered EntityManagerFactory
* persistence unit, provided that a discovered EntityManagerFactory
* implements the {@link EntityManagerFactoryInfo} interface. If not,
* the persistence unit name will be matched against the Spring bean name,
* assuming that the EntityManagerFactory bean names follow that convention.
* <p>If no unit name has been given, this method will search for a default
* EntityManagerFactory through {@link ListableBeanFactory#getBean(Class)}.
* @param beanFactory the ListableBeanFactory to search
* @param unitName the name of the persistence unit (may be {@code null} or empty,
* in which case a single bean of type EntityManagerFactory will be searched for)
@@ -108,7 +110,8 @@ public abstract class EntityManagerFactoryUtils {
return beanFactory.getBean(unitName, EntityManagerFactory.class);
}
else {
return BeanFactoryUtils.beanOfType(beanFactory, EntityManagerFactory.class);
// Find unique EntityManagerFactory bean in the context, falling back to parent contexts.
return beanFactory.getBean(EntityManagerFactory.class);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -43,6 +43,7 @@ import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.annotation.InjectionMetadata;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
@@ -60,7 +61,6 @@ import org.springframework.orm.jpa.ExtendedEntityManagerCreator;
import org.springframework.orm.jpa.SharedEntityManagerCreator;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* BeanPostProcessor that processes {@link javax.persistence.PersistenceUnit}
@@ -534,10 +534,11 @@ public class PersistenceAnnotationBeanPostProcessor
}
return emf;
}
else if (beanNames.length > 1) {
throw new NoUniqueBeanDefinitionException(EntityManagerFactory.class, beanNames);
}
else {
throw new NoSuchBeanDefinitionException(
EntityManagerFactory.class, "expected single bean but found " + beanNames.length + ": " +
StringUtils.arrayToCommaDelimitedString(beanNames));
throw new NoSuchBeanDefinitionException(EntityManagerFactory.class);
}
}

View File

@@ -1,36 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import org.springframework.core.enums.ShortCodedLabeledEnum;
/**
* @author Rob Harrop
*/
@SuppressWarnings("serial")
public class Colour extends ShortCodedLabeledEnum {
public static final Colour RED = new Colour(0, "RED");
public static final Colour BLUE = new Colour(1, "BLUE");
public static final Colour GREEN = new Colour(2, "GREEN");
public static final Colour PURPLE = new Colour(3, "PURPLE");
private Colour(int code, String label) {
super(code, label);
}
}

View File

@@ -1,23 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
public interface INestedTestBean {
public String getCompany();
}

View File

@@ -1,24 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
public interface IOther {
void absquatulate();
}

View File

@@ -1,71 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.io.IOException;
/**
* Interface used for {@link org.springframework.beans.TestBean}.
*
* <p>Two methods are the same as on Person, but if this
* extends person it breaks quite a few tests..
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
public interface ITestBean {
int getAge();
void setAge(int age);
String getName();
void setName(String name);
ITestBean getSpouse();
void setSpouse(ITestBean spouse);
ITestBean[] getSpouses();
String[] getStringArray();
void setStringArray(String[] stringArray);
/**
* Throws a given (non-null) exception.
*/
void exceptional(Throwable t) throws Throwable;
Object returnsThis();
INestedTestBean getDoctor();
INestedTestBean getLawyer();
IndexedTestBean getNestedIndexedBean();
/**
* Increment the age by one.
* @return the previous age
*/
int haveBirthday();
void unreliableFileOperation() throws IOException;
}

View File

@@ -1,145 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* @author Juergen Hoeller
* @since 11.11.2003
*/
public class IndexedTestBean {
private TestBean[] array;
private Collection collection;
private List list;
private Set set;
private SortedSet sortedSet;
private Map map;
private SortedMap sortedMap;
public IndexedTestBean() {
this(true);
}
public IndexedTestBean(boolean populate) {
if (populate) {
populate();
}
}
public void populate() {
TestBean tb0 = new TestBean("name0", 0);
TestBean tb1 = new TestBean("name1", 0);
TestBean tb2 = new TestBean("name2", 0);
TestBean tb3 = new TestBean("name3", 0);
TestBean tb4 = new TestBean("name4", 0);
TestBean tb5 = new TestBean("name5", 0);
TestBean tb6 = new TestBean("name6", 0);
TestBean tb7 = new TestBean("name7", 0);
TestBean tbX = new TestBean("nameX", 0);
TestBean tbY = new TestBean("nameY", 0);
this.array = new TestBean[] {tb0, tb1};
this.list = new ArrayList();
this.list.add(tb2);
this.list.add(tb3);
this.set = new TreeSet();
this.set.add(tb6);
this.set.add(tb7);
this.map = new HashMap();
this.map.put("key1", tb4);
this.map.put("key2", tb5);
this.map.put("key.3", tb5);
List list = new ArrayList();
list.add(tbX);
list.add(tbY);
this.map.put("key4", list);
}
public TestBean[] getArray() {
return array;
}
public void setArray(TestBean[] array) {
this.array = array;
}
public Collection getCollection() {
return collection;
}
public void setCollection(Collection collection) {
this.collection = collection;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public Set getSet() {
return set;
}
public void setSet(Set set) {
this.set = set;
}
public SortedSet getSortedSet() {
return sortedSet;
}
public void setSortedSet(SortedSet sortedSet) {
this.sortedSet = sortedSet;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
public SortedMap getSortedMap() {
return sortedMap;
}
public void setSortedMap(SortedMap sortedMap) {
this.sortedMap = sortedMap;
}
}

View File

@@ -1,61 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
/**
* Simple nested test bean used for testing bean factories, AOP framework etc.
*
* @author Trevor D. Cook
* @since 30.09.2003
*/
public class NestedTestBean implements INestedTestBean {
private String company = "";
public NestedTestBean() {
}
public NestedTestBean(String company) {
setCompany(company);
}
public void setCompany(String company) {
this.company = (company != null ? company : "");
}
@Override
public String getCompany() {
return company;
}
public boolean equals(Object obj) {
if (!(obj instanceof NestedTestBean)) {
return false;
}
NestedTestBean ntb = (NestedTestBean) obj;
return this.company.equals(ntb.company);
}
public int hashCode() {
return this.company.hashCode();
}
public String toString() {
return "NestedTestBean: " + this.company;
}
}

View File

@@ -1,457 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.util.ObjectUtils;
/**
* Simple test bean used for testing bean factories, the AOP framework etc.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 15 April 2001
*/
public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable {
private String beanName;
private String country;
private BeanFactory beanFactory;
private boolean postProcessed;
private String name;
private String sex;
private int age;
private boolean jedi;
private ITestBean[] spouses;
private String touchy;
private String[] stringArray;
private Integer[] someIntegerArray;
private Date date = new Date();
private Float myFloat = new Float(0.0);
private Collection friends = new LinkedList();
private Set someSet = new HashSet();
private Map someMap = new HashMap();
private List someList = new ArrayList();
private Properties someProperties = new Properties();
private INestedTestBean doctor = new NestedTestBean();
private INestedTestBean lawyer = new NestedTestBean();
private IndexedTestBean nestedIndexedBean;
private boolean destroyed;
private Number someNumber;
private Colour favouriteColour;
private Boolean someBoolean;
private List otherColours;
private List pets;
public TestBean() {
}
public TestBean(String name) {
this.name = name;
}
public TestBean(ITestBean spouse) {
this.spouses = new ITestBean[] {spouse};
}
public TestBean(String name, int age) {
this.name = name;
this.age = age;
}
public TestBean(ITestBean spouse, Properties someProperties) {
this.spouses = new ITestBean[] {spouse};
this.someProperties = someProperties;
}
public TestBean(List someList) {
this.someList = someList;
}
public TestBean(Set someSet) {
this.someSet = someSet;
}
public TestBean(Map someMap) {
this.someMap = someMap;
}
public TestBean(Properties someProperties) {
this.someProperties = someProperties;
}
@Override
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getBeanName() {
return beanName;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
public BeanFactory getBeanFactory() {
return beanFactory;
}
public void setPostProcessed(boolean postProcessed) {
this.postProcessed = postProcessed;
}
public boolean isPostProcessed() {
return postProcessed;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
if (this.name == null) {
this.name = sex;
}
}
@Override
public int getAge() {
return age;
}
@Override
public void setAge(int age) {
this.age = age;
}
public boolean isJedi() {
return jedi;
}
public void setJedi(boolean jedi) {
this.jedi = jedi;
}
@Override
public ITestBean getSpouse() {
return (spouses != null ? spouses[0] : null);
}
@Override
public void setSpouse(ITestBean spouse) {
this.spouses = new ITestBean[] {spouse};
}
@Override
public ITestBean[] getSpouses() {
return spouses;
}
public String getTouchy() {
return touchy;
}
public void setTouchy(String touchy) throws Exception {
if (touchy.indexOf('.') != -1) {
throw new Exception("Can't contain a .");
}
if (touchy.indexOf(',') != -1) {
throw new NumberFormatException("Number format exception: contains a ,");
}
this.touchy = touchy;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String[] getStringArray() {
return stringArray;
}
@Override
public void setStringArray(String[] stringArray) {
this.stringArray = stringArray;
}
public Integer[] getSomeIntegerArray() {
return someIntegerArray;
}
public void setSomeIntegerArray(Integer[] someIntegerArray) {
this.someIntegerArray = someIntegerArray;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Float getMyFloat() {
return myFloat;
}
public void setMyFloat(Float myFloat) {
this.myFloat = myFloat;
}
public Collection getFriends() {
return friends;
}
public void setFriends(Collection friends) {
this.friends = friends;
}
public Set getSomeSet() {
return someSet;
}
public void setSomeSet(Set someSet) {
this.someSet = someSet;
}
public Map getSomeMap() {
return someMap;
}
public void setSomeMap(Map someMap) {
this.someMap = someMap;
}
public List getSomeList() {
return someList;
}
public void setSomeList(List someList) {
this.someList = someList;
}
public Properties getSomeProperties() {
return someProperties;
}
public void setSomeProperties(Properties someProperties) {
this.someProperties = someProperties;
}
@Override
public INestedTestBean getDoctor() {
return doctor;
}
public void setDoctor(INestedTestBean doctor) {
this.doctor = doctor;
}
@Override
public INestedTestBean getLawyer() {
return lawyer;
}
public void setLawyer(INestedTestBean lawyer) {
this.lawyer = lawyer;
}
public Number getSomeNumber() {
return someNumber;
}
public void setSomeNumber(Number someNumber) {
this.someNumber = someNumber;
}
public Colour getFavouriteColour() {
return favouriteColour;
}
public void setFavouriteColour(Colour favouriteColour) {
this.favouriteColour = favouriteColour;
}
public Boolean getSomeBoolean() {
return someBoolean;
}
public void setSomeBoolean(Boolean someBoolean) {
this.someBoolean = someBoolean;
}
@Override
public IndexedTestBean getNestedIndexedBean() {
return nestedIndexedBean;
}
public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) {
this.nestedIndexedBean = nestedIndexedBean;
}
public List getOtherColours() {
return otherColours;
}
public void setOtherColours(List otherColours) {
this.otherColours = otherColours;
}
public List getPets() {
return pets;
}
public void setPets(List pets) {
this.pets = pets;
}
/**
* @see org.springframework.beans.ITestBean#exceptional(Throwable)
*/
@Override
public void exceptional(Throwable t) throws Throwable {
if (t != null) {
throw t;
}
}
@Override
public void unreliableFileOperation() throws IOException {
throw new IOException();
}
/**
* @see org.springframework.beans.ITestBean#returnsThis()
*/
@Override
public Object returnsThis() {
return this;
}
/**
* @see org.springframework.beans.IOther#absquatulate()
*/
@Override
public void absquatulate() {
}
@Override
public int haveBirthday() {
return age++;
}
public void destroy() {
this.destroyed = true;
}
public boolean wasDestroyed() {
return destroyed;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || !(other instanceof TestBean)) {
return false;
}
TestBean tb2 = (TestBean) other;
return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age);
}
public int hashCode() {
return this.age;
}
@Override
public int compareTo(Object other) {
if (this.name != null && other instanceof TestBean) {
return this.name.compareTo(((TestBean) other).getName());
}
else {
return 1;
}
}
public String toString() {
return this.name;
}
}

View File

@@ -1,88 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.config;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.ObjectFactory;
/**
* @author Juergen Hoeller
*/
@SuppressWarnings("serial")
public class SimpleMapScope implements Scope, Serializable {
private final Map map = new HashMap();
private final List callbacks = new LinkedList();
public SimpleMapScope() {
}
public final Map getMap() {
return this.map;
}
@Override
public Object get(String name, ObjectFactory objectFactory) {
synchronized (this.map) {
Object scopedObject = this.map.get(name);
if (scopedObject == null) {
scopedObject = objectFactory.getObject();
this.map.put(name, scopedObject);
}
return scopedObject;
}
}
@Override
public Object remove(String name) {
synchronized (this.map) {
return this.map.remove(name);
}
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
this.callbacks.add(callback);
}
@Override
public Object resolveContextualObject(String key) {
return null;
}
public void close() {
for (Iterator it = this.callbacks.iterator(); it.hasNext();) {
Runnable runnable = (Runnable) it.next();
runnable.run();
}
}
@Override
public String getConversationId() {
return null;
}
}

View File

@@ -1,82 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.jndi;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.naming.NamingException;
import org.springframework.jndi.JndiTemplate;
/**
* Simple extension of the JndiTemplate class that always returns
* a given object. Very useful for testing. Effectively a mock object.
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class ExpectedLookupTemplate extends JndiTemplate {
private final Map<String, Object> jndiObjects = new ConcurrentHashMap<String, Object>();
/**
* Construct a new JndiTemplate that will always return given objects
* for given names. To be populated through {@code addObject} calls.
* @see #addObject(String, Object)
*/
public ExpectedLookupTemplate() {
}
/**
* Construct a new JndiTemplate that will always return the
* given object, but honour only requests for the given name.
* @param name the name the client is expected to look up
* @param object the object that will be returned
*/
public ExpectedLookupTemplate(String name, Object object) {
addObject(name, object);
}
/**
* Add the given object to the list of JNDI objects that this
* template will expose.
* @param name the name the client is expected to look up
* @param object the object that will be returned
*/
public void addObject(String name, Object object) {
this.jndiObjects.put(name, object);
}
/**
* If the name is the expected name specified in the constructor,
* return the object provided in the constructor. If the name is
* unexpected, a respective NamingException gets thrown.
*/
@Override
public Object lookup(String name) throws NamingException {
Object object = this.jndiObjects.get(name);
if (object == null) {
throw new NamingException("Unexpected JNDI name '" + name + "': expecting " + this.jndiObjects.keySet());
}
return object;
}
}

View File

@@ -1,381 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.jndi;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameNotFoundException;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.OperationNotSupportedException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
/**
* Simple implementation of a JNDI naming context.
* Only supports binding plain Objects to String names.
* Mainly for test environments, but also usable for standalone applications.
*
* <p>This class is not intended for direct usage by applications, although it
* can be used for example to override JndiTemplate's {@code createInitialContext}
* method in unit tests. Typically, SimpleNamingContextBuilder will be used to
* set up a JVM-level JNDI environment.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see SimpleNamingContextBuilder
* @see org.springframework.jndi.JndiTemplate#createInitialContext
*/
public class SimpleNamingContext implements Context {
private final Log logger = LogFactory.getLog(getClass());
private final String root;
private final Hashtable<String, Object> boundObjects;
private final Hashtable<String, Object> environment = new Hashtable<String, Object>();
/**
* Create a new naming context.
*/
public SimpleNamingContext() {
this("");
}
/**
* Create a new naming context with the given naming root.
*/
public SimpleNamingContext(String root) {
this.root = root;
this.boundObjects = new Hashtable<String, Object>();
}
/**
* Create a new naming context with the given naming root,
* the given name/object map, and the JNDI environment entries.
*/
public SimpleNamingContext(String root, Hashtable<String, Object> boundObjects, Hashtable<String, Object> env) {
this.root = root;
this.boundObjects = boundObjects;
if (env != null) {
this.environment.putAll(env);
}
}
// Actual implementations of Context methods follow
@Override
public NamingEnumeration<NameClassPair> list(String root) throws NamingException {
if (logger.isDebugEnabled()) {
logger.debug("Listing name/class pairs under [" + root + "]");
}
return new NameClassPairEnumeration(this, root);
}
@Override
public NamingEnumeration<Binding> listBindings(String root) throws NamingException {
if (logger.isDebugEnabled()) {
logger.debug("Listing bindings under [" + root + "]");
}
return new BindingEnumeration(this, root);
}
/**
* Look up the object with the given name.
* <p>Note: Not intended for direct use by applications.
* Will be used by any standard InitialContext JNDI lookups.
* @throws javax.naming.NameNotFoundException if the object could not be found
*/
@Override
public Object lookup(String lookupName) throws NameNotFoundException {
String name = this.root + lookupName;
if (logger.isDebugEnabled()) {
logger.debug("Static JNDI lookup: [" + name + "]");
}
if ("".equals(name)) {
return new SimpleNamingContext(this.root, this.boundObjects, this.environment);
}
Object found = this.boundObjects.get(name);
if (found == null) {
if (!name.endsWith("/")) {
name = name + "/";
}
for (String boundName : this.boundObjects.keySet()) {
if (boundName.startsWith(name)) {
return new SimpleNamingContext(name, this.boundObjects, this.environment);
}
}
throw new NameNotFoundException(
"Name [" + this.root + lookupName + "] not bound; " + this.boundObjects.size() + " bindings: [" +
StringUtils.collectionToDelimitedString(this.boundObjects.keySet(), ",") + "]");
}
return found;
}
@Override
public Object lookupLink(String name) throws NameNotFoundException {
return lookup(name);
}
/**
* Bind the given object to the given name.
* Note: Not intended for direct use by applications
* if setting up a JVM-level JNDI environment.
* Use SimpleNamingContextBuilder to set up JNDI bindings then.
* @see org.springframework.mock.jndi.SimpleNamingContextBuilder#bind
*/
@Override
public void bind(String name, Object obj) {
if (logger.isInfoEnabled()) {
logger.info("Static JNDI binding: [" + this.root + name + "] = [" + obj + "]");
}
this.boundObjects.put(this.root + name, obj);
}
@Override
public void unbind(String name) {
if (logger.isInfoEnabled()) {
logger.info("Static JNDI remove: [" + this.root + name + "]");
}
this.boundObjects.remove(this.root + name);
}
@Override
public void rebind(String name, Object obj) {
bind(name, obj);
}
@Override
public void rename(String oldName, String newName) throws NameNotFoundException {
Object obj = lookup(oldName);
unbind(oldName);
bind(newName, obj);
}
@Override
public Context createSubcontext(String name) {
String subcontextName = this.root + name;
if (!subcontextName.endsWith("/")) {
subcontextName += "/";
}
Context subcontext = new SimpleNamingContext(subcontextName, this.boundObjects, this.environment);
bind(name, subcontext);
return subcontext;
}
@Override
public void destroySubcontext(String name) {
unbind(name);
}
@Override
public String composeName(String name, String prefix) {
return prefix + name;
}
@Override
public Hashtable<String, Object> getEnvironment() {
return this.environment;
}
@Override
public Object addToEnvironment(String propName, Object propVal) {
return this.environment.put(propName, propVal);
}
@Override
public Object removeFromEnvironment(String propName) {
return this.environment.remove(propName);
}
@Override
public void close() {
}
// Unsupported methods follow: no support for javax.naming.Name
@Override
public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public Object lookup(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public Object lookupLink(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public void bind(Name name, Object obj) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public void unbind(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public void rebind(Name name, Object obj) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public void rename(Name oldName, Name newName) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public Context createSubcontext(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public void destroySubcontext(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public String getNameInNamespace() throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public NameParser getNameParser(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public NameParser getNameParser(String name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public Name composeName(Name name, Name prefix) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
private static abstract class AbstractNamingEnumeration<T> implements NamingEnumeration<T> {
private Iterator<T> iterator;
private AbstractNamingEnumeration(SimpleNamingContext context, String proot) throws NamingException {
if (!"".equals(proot) && !proot.endsWith("/")) {
proot = proot + "/";
}
String root = context.root + proot;
Map<String, T> contents = new HashMap<String, T>();
for (String boundName : context.boundObjects.keySet()) {
if (boundName.startsWith(root)) {
int startIndex = root.length();
int endIndex = boundName.indexOf('/', startIndex);
String strippedName =
(endIndex != -1 ? boundName.substring(startIndex, endIndex) : boundName.substring(startIndex));
if (!contents.containsKey(strippedName)) {
try {
contents.put(strippedName, createObject(strippedName, context.lookup(proot + strippedName)));
}
catch (NameNotFoundException ex) {
// cannot happen
}
}
}
}
if (contents.size() == 0) {
throw new NamingException("Invalid root: [" + context.root + proot + "]");
}
this.iterator = contents.values().iterator();
}
protected abstract T createObject(String strippedName, Object obj);
@Override
public boolean hasMore() {
return this.iterator.hasNext();
}
@Override
public T next() {
return this.iterator.next();
}
@Override
public boolean hasMoreElements() {
return this.iterator.hasNext();
}
@Override
public T nextElement() {
return this.iterator.next();
}
@Override
public void close() {
}
}
private static class NameClassPairEnumeration extends AbstractNamingEnumeration<NameClassPair> {
private NameClassPairEnumeration(SimpleNamingContext context, String root) throws NamingException {
super(context, root);
}
@Override
protected NameClassPair createObject(String strippedName, Object obj) {
return new NameClassPair(strippedName, obj.getClass().getName());
}
}
private static class BindingEnumeration extends AbstractNamingEnumeration<Binding> {
private BindingEnumeration(SimpleNamingContext context, String root) throws NamingException {
super(context, root);
}
@Override
protected Binding createObject(String strippedName, Object obj) {
return new Binding(strippedName, obj);
}
}
}

View File

@@ -1,237 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.jndi;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;
import javax.naming.spi.InitialContextFactoryBuilder;
import javax.naming.spi.NamingManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.ClassUtils;
/**
* Simple implementation of a JNDI naming context builder.
*
* <p>Mainly targeted at test environments, where each test case can
* configure JNDI appropriately, so that {@code new InitialContext()}
* will expose the required objects. Also usable for standalone applications,
* e.g. for binding a JDBC DataSource to a well-known JNDI location, to be
* able to use traditional J2EE data access code outside of a J2EE container.
*
* <p>There are various choices for DataSource implementations:
* <ul>
* <li>SingleConnectionDataSource (using the same Connection for all getConnection calls);
* <li>DriverManagerDataSource (creating a new Connection on each getConnection call);
* <li>Apache's Jakarta Commons DBCP offers BasicDataSource (a real pool).
* </ul>
*
* <p>Typical usage in bootstrap code:
*
* <pre class="code">
* SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
* DataSource ds = new DriverManagerDataSource(...);
* builder.bind("java:comp/env/jdbc/myds", ds);
* builder.activate();</pre>
*
* Note that it's impossible to activate multiple builders within the same JVM,
* due to JNDI restrictions. Thus to configure a fresh builder repeatedly, use
* the following code to get a reference to either an already activated builder
* or a newly activated one:
*
* <pre class="code">
* SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
* DataSource ds = new DriverManagerDataSource(...);
* builder.bind("java:comp/env/jdbc/myds", ds);</pre>
*
* Note that you <i>should not</i> call {@code activate()} on a builder from
* this factory method, as there will already be an activated one in any case.
*
* <p>An instance of this class is only necessary at setup time.
* An application does not need to keep a reference to it after activation.
*
* @author Juergen Hoeller
* @author Rod Johnson
* @see #emptyActivatedContextBuilder()
* @see #bind(String, Object)
* @see #activate()
* @see SimpleNamingContext
* @see org.springframework.jdbc.datasource.SingleConnectionDataSource
* @see org.springframework.jdbc.datasource.DriverManagerDataSource
* @see org.apache.commons.dbcp.BasicDataSource
*/
public class SimpleNamingContextBuilder implements InitialContextFactoryBuilder {
/** An instance of this class bound to JNDI */
private static volatile SimpleNamingContextBuilder activated;
private static boolean initialized = false;
private static final Object initializationLock = new Object();
/**
* Checks if a SimpleNamingContextBuilder is active.
* @return the current SimpleNamingContextBuilder instance,
* or {@code null} if none
*/
public static SimpleNamingContextBuilder getCurrentContextBuilder() {
return activated;
}
/**
* If no SimpleNamingContextBuilder is already configuring JNDI,
* create and activate one. Otherwise take the existing activate
* SimpleNamingContextBuilder, clear it and return it.
* <p>This is mainly intended for test suites that want to
* reinitialize JNDI bindings from scratch repeatedly.
* @return an empty SimpleNamingContextBuilder that can be used
* to control JNDI bindings
*/
public static SimpleNamingContextBuilder emptyActivatedContextBuilder() throws NamingException {
if (activated != null) {
// Clear already activated context builder.
activated.clear();
}
else {
// Create and activate new context builder.
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
// The activate() call will cause an assignment to the activated variable.
builder.activate();
}
return activated;
}
private final Log logger = LogFactory.getLog(getClass());
private final Hashtable<String,Object> boundObjects = new Hashtable<String,Object>();
/**
* Register the context builder by registering it with the JNDI NamingManager.
* Note that once this has been done, {@code new InitialContext()} will always
* return a context from this factory. Use the {@code emptyActivatedContextBuilder()}
* static method to get an empty context (for example, in test methods).
* @throws IllegalStateException if there's already a naming context builder
* registered with the JNDI NamingManager
*/
public void activate() throws IllegalStateException, NamingException {
logger.info("Activating simple JNDI environment");
synchronized (initializationLock) {
if (!initialized) {
if (NamingManager.hasInitialContextFactoryBuilder()) {
throw new IllegalStateException(
"Cannot activate SimpleNamingContextBuilder: there is already a JNDI provider registered. " +
"Note that JNDI is a JVM-wide service, shared at the JVM system class loader level, " +
"with no reset option. As a consequence, a JNDI provider must only be registered once per JVM.");
}
NamingManager.setInitialContextFactoryBuilder(this);
initialized = true;
}
}
activated = this;
}
/**
* Temporarily deactivate this context builder. It will remain registered with
* the JNDI NamingManager but will delegate to the standard JNDI InitialContextFactory
* (if configured) instead of exposing its own bound objects.
* <p>Call {@code activate()} again in order to expose this context builder's own
* bound objects again. Such activate/deactivate sequences can be applied any number
* of times (e.g. within a larger integration test suite running in the same VM).
* @see #activate()
*/
public void deactivate() {
logger.info("Deactivating simple JNDI environment");
activated = null;
}
/**
* Clear all bindings in this context builder, while keeping it active.
*/
public void clear() {
this.boundObjects.clear();
}
/**
* Bind the given object under the given name, for all naming contexts
* that this context builder will generate.
* @param name the JNDI name of the object (e.g. "java:comp/env/jdbc/myds")
* @param obj the object to bind (e.g. a DataSource implementation)
*/
public void bind(String name, Object obj) {
if (logger.isInfoEnabled()) {
logger.info("Static JNDI binding: [" + name + "] = [" + obj + "]");
}
this.boundObjects.put(name, obj);
}
/**
* Simple InitialContextFactoryBuilder implementation,
* creating a new SimpleNamingContext instance.
* @see SimpleNamingContext
*/
@Override
public InitialContextFactory createInitialContextFactory(Hashtable<?,?> environment) {
if (activated == null && environment != null) {
Object icf = environment.get(Context.INITIAL_CONTEXT_FACTORY);
if (icf != null) {
Class<?> icfClass = null;
if (icf instanceof Class) {
icfClass = (Class<?>) icf;
}
else if (icf instanceof String) {
icfClass = ClassUtils.resolveClassName((String) icf, getClass().getClassLoader());
}
else {
throw new IllegalArgumentException("Invalid value type for environment key [" +
Context.INITIAL_CONTEXT_FACTORY + "]: " + icf.getClass().getName());
}
if (!InitialContextFactory.class.isAssignableFrom(icfClass)) {
throw new IllegalArgumentException(
"Specified class does not implement [" + InitialContextFactory.class.getName() + "]: " + icf);
}
try {
return (InitialContextFactory) icfClass.newInstance();
}
catch (Throwable ex) {
IllegalStateException ise =
new IllegalStateException("Cannot instantiate specified InitialContextFactory: " + icf);
ise.initCause(ex);
throw ise;
}
}
}
// Default case...
return new InitialContextFactory() {
@Override
@SuppressWarnings("unchecked")
public Context getInitialContext(Hashtable<?,?> environment) {
return new SimpleNamingContext("", boundObjects, (Hashtable<String, Object>) environment);
}
};
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,389 +16,293 @@
package org.springframework.orm.hibernate3;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.sql.SQLException;
import junit.framework.TestCase;
import org.aopalliance.intercept.Interceptor;
import org.aopalliance.intercept.Invocation;
import org.aopalliance.intercept.MethodInvocation;
import org.easymock.MockControl;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.exception.ConstraintViolationException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* @author Juergen Hoeller
* @author Phillip Webb
* @since 05.03.2005
*/
public class HibernateInterceptorTests extends TestCase {
public class HibernateInterceptorTests {
private SessionFactory sessionFactory;
private Session session;
private MethodInvocation invocation;
@Before
public void setUp() throws Throwable {
this.sessionFactory = mock(SessionFactory.class);
this.session = mock(Session.class);
this.invocation = mock(MethodInvocation.class);
given(sessionFactory.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sessionFactory);
given(invocation.proceed()).willAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
if (!TransactionSynchronizationManager.hasResource(sessionFactory)) {
throw new IllegalStateException("Session not bound");
}
return null;
}
});
}
@After
public void tearDown() {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
@Test
public void testInterceptorWithNewSession() throws HibernateException {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
session.getSessionFactory();
sessionControl.setReturnValue(sf);
session.flush();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setReturnValue(null, 1);
sfControl.replay();
sessionControl.replay();
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setSessionFactory(sessionFactory);
try {
interceptor.invoke(new TestInvocation(sf));
interceptor.invoke(invocation);
}
catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
sfControl.verify();
sessionControl.verify();
verify(session).flush();
verify(session).close();
}
@Test
public void testInterceptorWithNewSessionAndFlushNever() throws HibernateException {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
session.getSessionFactory();
sessionControl.setReturnValue(sf);
session.setFlushMode(FlushMode.MANUAL);
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setReturnValue(null, 1);
sfControl.replay();
sessionControl.replay();
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setFlushModeName("FLUSH_NEVER");
interceptor.setSessionFactory(sf);
interceptor.setSessionFactory(sessionFactory);
try {
interceptor.invoke(new TestInvocation(sf));
interceptor.invoke(invocation);
}
catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
sfControl.verify();
sessionControl.verify();
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session, never()).flush();
verify(session).close();
}
@Test
public void testInterceptorWithNewSessionAndFilter() throws HibernateException {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
session.getSessionFactory();
sessionControl.setReturnValue(sf);
session.enableFilter("myFilter");
sessionControl.setReturnValue(null, 1);
session.flush();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setReturnValue(null, 1);
sfControl.replay();
sessionControl.replay();
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setSessionFactory(sessionFactory);
interceptor.setFilterName("myFilter");
try {
interceptor.invoke(new TestInvocation(sf));
interceptor.invoke(invocation);
}
catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
sfControl.verify();
sessionControl.verify();
verify(session).flush();
verify(session).close();
}
@Test
public void testInterceptorWithThreadBound() {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
session.getSessionFactory();
sessionControl.setReturnValue(sf, 1);
session.isOpen();
sessionControl.setReturnValue(true, 1);
sfControl.replay();
sessionControl.replay();
given(session.isOpen()).willReturn(true);
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setSessionFactory(sessionFactory);
try {
interceptor.invoke(new TestInvocation(sf));
interceptor.invoke(invocation);
}
catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
finally {
TransactionSynchronizationManager.unbindResource(sf);
verify(session, never()).flush();
verify(session, never()).close();
TransactionSynchronizationManager.unbindResource(sessionFactory);
}
sfControl.verify();
sessionControl.verify();
}
@Test
public void testInterceptorWithThreadBoundAndFlushEager() throws HibernateException {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
session.getSessionFactory();
sessionControl.setReturnValue(sf, 1);
session.isOpen();
sessionControl.setReturnValue(true, 1);
session.getFlushMode();
sessionControl.setReturnValue(FlushMode.AUTO, 1);
session.flush();
sessionControl.setVoidCallable(1);
sfControl.replay();
sessionControl.replay();
given(session.isOpen()).willReturn(true);
given(session.getFlushMode()).willReturn(FlushMode.AUTO);
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setFlushMode(HibernateInterceptor.FLUSH_EAGER);
interceptor.setSessionFactory(sf);
interceptor.setSessionFactory(sessionFactory);
try {
interceptor.invoke(new TestInvocation(sf));
interceptor.invoke(invocation);
}
catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
finally {
TransactionSynchronizationManager.unbindResource(sf);
TransactionSynchronizationManager.unbindResource(sessionFactory);
}
sfControl.verify();
sessionControl.verify();
verify(session).flush();
}
@Test
public void testInterceptorWithThreadBoundAndFlushEagerSwitch() throws HibernateException {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
session.getSessionFactory();
sessionControl.setReturnValue(sf, 1);
session.isOpen();
sessionControl.setReturnValue(true, 1);
session.getFlushMode();
sessionControl.setReturnValue(FlushMode.NEVER, 1);
session.setFlushMode(FlushMode.AUTO);
sessionControl.setVoidCallable(1);
session.flush();
sessionControl.setVoidCallable(1);
session.setFlushMode(FlushMode.NEVER);
sessionControl.setVoidCallable(1);
sfControl.replay();
sessionControl.replay();
given(session.isOpen()).willReturn(true);
given(session.getFlushMode()).willReturn(FlushMode.NEVER);
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setFlushMode(HibernateInterceptor.FLUSH_EAGER);
interceptor.setSessionFactory(sf);
interceptor.setSessionFactory(sessionFactory);
try {
interceptor.invoke(new TestInvocation(sf));
interceptor.invoke(invocation);
}
catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
finally {
TransactionSynchronizationManager.unbindResource(sf);
TransactionSynchronizationManager.unbindResource(sessionFactory);
}
sfControl.verify();
sessionControl.verify();
InOrder ordered = inOrder(session);
ordered.verify(session).setFlushMode(FlushMode.AUTO);
ordered.verify(session).flush();
ordered.verify(session).setFlushMode(FlushMode.NEVER);
}
@Test
public void testInterceptorWithThreadBoundAndFlushCommit() {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
session.getSessionFactory();
sessionControl.setReturnValue(sf, 1);
session.isOpen();
sessionControl.setReturnValue(true, 1);
session.getFlushMode();
sessionControl.setReturnValue(FlushMode.AUTO, 1);
session.setFlushMode(FlushMode.COMMIT);
sessionControl.setVoidCallable(1);
session.setFlushMode(FlushMode.AUTO);
sessionControl.setVoidCallable(1);
sfControl.replay();
sessionControl.replay();
given(session.isOpen()).willReturn(true);
given(session.getFlushMode()).willReturn(FlushMode.AUTO);
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setSessionFactory(sessionFactory);
interceptor.setFlushMode(HibernateInterceptor.FLUSH_COMMIT);
try {
interceptor.invoke(new TestInvocation(sf));
interceptor.invoke(invocation);
}
catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
finally {
TransactionSynchronizationManager.unbindResource(sf);
TransactionSynchronizationManager.unbindResource(sessionFactory);
}
sfControl.verify();
sessionControl.verify();
InOrder ordered = inOrder(session);
ordered.verify(session).setFlushMode(FlushMode.COMMIT);
ordered.verify(session).setFlushMode(FlushMode.AUTO);
verify(session, never()).flush();
}
@Test
public void testInterceptorWithThreadBoundAndFlushAlways() {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
session.getSessionFactory();
sessionControl.setReturnValue(sf, 1);
session.isOpen();
sessionControl.setReturnValue(true, 1);
session.getFlushMode();
sessionControl.setReturnValue(FlushMode.AUTO, 1);
session.setFlushMode(FlushMode.ALWAYS);
sessionControl.setVoidCallable(1);
session.setFlushMode(FlushMode.AUTO);
sessionControl.setVoidCallable(1);
sfControl.replay();
sessionControl.replay();
given(session.isOpen()).willReturn(true);
given(session.getFlushMode()).willReturn(FlushMode.AUTO);
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setSessionFactory(sessionFactory);
interceptor.setFlushMode(HibernateInterceptor.FLUSH_ALWAYS);
try {
interceptor.invoke(new TestInvocation(sf));
interceptor.invoke(invocation);
}
catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
finally {
TransactionSynchronizationManager.unbindResource(sf);
TransactionSynchronizationManager.unbindResource(sessionFactory);
}
sfControl.verify();
sessionControl.verify();
InOrder ordered = inOrder(session);
ordered.verify(session).setFlushMode(FlushMode.ALWAYS);
ordered.verify(session).setFlushMode(FlushMode.AUTO);
verify(session, never()).flush();
}
@Test
public void testInterceptorWithThreadBoundAndFilter() {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
session.getSessionFactory();
sessionControl.setReturnValue(sf, 1);
session.isOpen();
sessionControl.setReturnValue(true, 1);
session.enableFilter("myFilter");
sessionControl.setReturnValue(null, 1);
session.disableFilter("myFilter");
sessionControl.setVoidCallable(1);
sfControl.replay();
sessionControl.replay();
given(session.isOpen()).willReturn(true);
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setSessionFactory(sessionFactory);
interceptor.setFilterName("myFilter");
try {
interceptor.invoke(new TestInvocation(sf));
interceptor.invoke(invocation);
}
catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
finally {
TransactionSynchronizationManager.unbindResource(sf);
TransactionSynchronizationManager.unbindResource(sessionFactory);
}
sfControl.verify();
sessionControl.verify();
InOrder ordered = inOrder(session);
ordered.verify(session).enableFilter("myFilter");
ordered.verify(session).disableFilter("myFilter");
}
@Test
public void testInterceptorWithThreadBoundAndFilters() {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
session.getSessionFactory();
sessionControl.setReturnValue(sf, 1);
session.isOpen();
sessionControl.setReturnValue(true, 1);
session.enableFilter("myFilter");
sessionControl.setReturnValue(null, 1);
session.enableFilter("yourFilter");
sessionControl.setReturnValue(null, 1);
session.disableFilter("myFilter");
sessionControl.setVoidCallable(1);
session.disableFilter("yourFilter");
sessionControl.setVoidCallable(1);
sfControl.replay();
sessionControl.replay();
given(session.isOpen()).willReturn(true);
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setSessionFactory(sessionFactory);
interceptor.setFilterNames(new String[] {"myFilter", "yourFilter"});
try {
interceptor.invoke(new TestInvocation(sf));
interceptor.invoke(invocation);
}
catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
finally {
TransactionSynchronizationManager.unbindResource(sf);
TransactionSynchronizationManager.unbindResource(sessionFactory);
}
sfControl.verify();
sessionControl.verify();
InOrder ordered = inOrder(session);
ordered.verify(session).enableFilter("myFilter");
ordered.verify(session).enableFilter("yourFilter");
ordered.verify(session).disableFilter("myFilter");
ordered.verify(session).disableFilter("yourFilter");
}
@Test
public void testInterceptorWithFlushFailure() throws Throwable {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
session.getSessionFactory();
sessionControl.setReturnValue(sf, 1);
SQLException sqlEx = new SQLException("argh", "27");
session.flush();
ConstraintViolationException jdbcEx = new ConstraintViolationException("", sqlEx, null);
sessionControl.setThrowable(jdbcEx, 1);
session.close();
sessionControl.setReturnValue(null, 1);
sfControl.replay();
sessionControl.replay();
willThrow(jdbcEx).given(session).flush();
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setSessionFactory(sessionFactory);
try {
interceptor.invoke(new TestInvocation(sf));
interceptor.invoke(invocation);
fail("Should have thrown DataIntegrityViolationException");
}
catch (DataIntegrityViolationException ex) {
@@ -406,204 +310,72 @@ public class HibernateInterceptorTests extends TestCase {
assertEquals(jdbcEx, ex.getCause());
}
sfControl.verify();
sessionControl.verify();
verify(session).close();
}
@Test
public void testInterceptorWithThreadBoundEmptyHolder() {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
session.getSessionFactory();
sessionControl.setReturnValue(sf, 1);
session.flush();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setReturnValue(null, 1);
sfControl.replay();
sessionControl.replay();
SessionHolder holder = new SessionHolder("key", session);
holder.removeSession("key");
TransactionSynchronizationManager.bindResource(sf, holder);
TransactionSynchronizationManager.bindResource(sessionFactory, holder);
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setSessionFactory(sessionFactory);
try {
interceptor.invoke(new TestInvocation(sf));
interceptor.invoke(invocation);
}
catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
sfControl.verify();
sessionControl.verify();
verify(session).flush();
verify(session).close();
}
@Test
public void testInterceptorWithEntityInterceptor() throws HibernateException {
MockControl interceptorControl = MockControl.createControl(org.hibernate.Interceptor.class);
org.hibernate.Interceptor entityInterceptor = (org.hibernate.Interceptor) interceptorControl.getMock();
interceptorControl.replay();
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
sf.openSession(entityInterceptor);
sfControl.setReturnValue(session, 1);
session.getSessionFactory();
sessionControl.setReturnValue(sf, 1);
session.flush();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setReturnValue(null, 1);
sfControl.replay();
sessionControl.replay();
org.hibernate.Interceptor entityInterceptor = mock(org.hibernate.Interceptor.class);
given(sessionFactory.openSession(entityInterceptor)).willReturn(session);
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setSessionFactory(sessionFactory);
interceptor.setEntityInterceptor(entityInterceptor);
try {
interceptor.invoke(new TestInvocation(sf));
interceptor.invoke(invocation);
}
catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
interceptorControl.verify();
sfControl.verify();
sessionControl.verify();
verify(session).flush();
verify(session).close();
}
@Test
public void testInterceptorWithEntityInterceptorBeanName() throws HibernateException {
MockControl interceptorControl = MockControl.createControl(org.hibernate.Interceptor.class);
org.hibernate.Interceptor entityInterceptor = (org.hibernate.Interceptor) interceptorControl.getMock();
interceptorControl.replay();
MockControl interceptor2Control = MockControl.createControl(org.hibernate.Interceptor.class);
org.hibernate.Interceptor entityInterceptor2 = (org.hibernate.Interceptor) interceptor2Control.getMock();
interceptor2Control.replay();
org.hibernate.Interceptor entityInterceptor = mock(org.hibernate.Interceptor.class);
org.hibernate.Interceptor entityInterceptor2 = mock(org.hibernate.Interceptor.class);
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
sf.openSession(entityInterceptor);
sfControl.setReturnValue(session, 1);
sf.openSession(entityInterceptor2);
sfControl.setReturnValue(session, 1);
session.getSessionFactory();
sessionControl.setReturnValue(sf, 2);
session.flush();
sessionControl.setVoidCallable(2);
session.close();
sessionControl.setReturnValue(null, 2);
sfControl.replay();
sessionControl.replay();
given(sessionFactory.openSession(entityInterceptor)).willReturn(session);
given(sessionFactory.openSession(entityInterceptor2)).willReturn(session);
MockControl beanFactoryControl = MockControl.createControl(BeanFactory.class);
BeanFactory beanFactory = (BeanFactory) beanFactoryControl.getMock();
beanFactory.getBean("entityInterceptor", org.hibernate.Interceptor.class);
beanFactoryControl.setReturnValue(entityInterceptor, 1);
beanFactory.getBean("entityInterceptor", org.hibernate.Interceptor.class);
beanFactoryControl.setReturnValue(entityInterceptor2, 1);
beanFactoryControl.replay();
BeanFactory beanFactory = mock(BeanFactory.class);
given(beanFactory.getBean("entityInterceptor", org.hibernate.Interceptor.class)).willReturn(
entityInterceptor, entityInterceptor2);
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setSessionFactory(sessionFactory);
interceptor.setEntityInterceptorBeanName("entityInterceptor");
interceptor.setBeanFactory(beanFactory);
for (int i = 0; i < 2; i++) {
try {
interceptor.invoke(new TestInvocation(sf));
interceptor.invoke(invocation);
}
catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
}
interceptorControl.verify();
interceptor2Control.verify();
sfControl.verify();
sessionControl.verify();
verify(session, times(2)).flush();
verify(session, times(2)).close();
}
@Override
protected void tearDown() {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
private static class TestInvocation implements MethodInvocation {
private SessionFactory sessionFactory;
public TestInvocation(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public Object proceed() throws Throwable {
if (!TransactionSynchronizationManager.hasResource(this.sessionFactory)) {
throw new IllegalStateException("Session not bound");
}
return null;
}
public int getCurrentInterceptorIndex() {
return 0;
}
public int getNumberOfInterceptors() {
return 0;
}
public Interceptor getInterceptor(int i) {
return null;
}
@Override
public Method getMethod() {
return null;
}
@Override
public AccessibleObject getStaticPart() {
return null;
}
public Object getArgument(int i) {
return null;
}
@Override
public Object[] getArguments() {
return null;
}
public void setArgument(int i, Object handler) {
}
public int getArgumentCount() {
return 0;
}
@Override
public Object getThis() {
return null;
}
public Object getProxy() {
return null;
}
public Invocation cloneInstance() {
return null;
}
public void release() {
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,13 @@
package org.springframework.orm.hibernate3;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -31,9 +38,6 @@ import java.util.Set;
import javax.transaction.TransactionManager;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.hibernate.HibernateException;
import org.hibernate.Interceptor;
import org.hibernate.SessionFactory;
@@ -51,6 +55,7 @@ import org.hibernate.engine.FilterDefinition;
import org.hibernate.event.MergeEvent;
import org.hibernate.event.MergeEventListener;
import org.hibernate.mapping.TypeDef;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
@@ -60,10 +65,12 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**
* @author Juergen Hoeller
* @author Phillip Webb
* @since 05.03.2005
*/
public class LocalSessionFactoryBeanTests extends TestCase {
public class LocalSessionFactoryBeanTests {
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithDataSource() throws Exception {
final DriverManagerDataSource ds = new DriverManagerDataSource();
@@ -99,6 +106,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
assertEquals("newSessionFactory", invocations.get(0));
}
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithCacheRegionFactory() throws Exception {
final RegionFactory regionFactory = new NoCachingRegionFactory(null);
@@ -134,6 +142,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
assertEquals("newSessionFactory", invocations.get(0));
}
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithCacheProvider() throws Exception {
final CacheProvider cacheProvider = new NoCacheProvider();
@@ -170,6 +179,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
assertEquals("newSessionFactory", invocations.get(0));
}
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithTransactionAwareDataSource() throws Exception {
final DriverManagerDataSource ds = new DriverManagerDataSource();
@@ -207,11 +217,11 @@ public class LocalSessionFactoryBeanTests extends TestCase {
assertEquals("newSessionFactory", invocations.get(0));
}
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithDataSourceAndMappingResources() throws Exception {
final DriverManagerDataSource ds = new DriverManagerDataSource();
MockControl tmControl = MockControl.createControl(TransactionManager.class);
final TransactionManager tm = (TransactionManager) tmControl.getMock();
final TransactionManager tm = mock(TransactionManager.class);
final List invocations = new ArrayList();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
@@ -254,6 +264,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
assertEquals("newSessionFactory", invocations.get(2));
}
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithDataSourceAndMappingJarLocations() throws Exception {
final DriverManagerDataSource ds = new DriverManagerDataSource();
@@ -289,6 +300,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
assertTrue(invocations.contains("newSessionFactory"));
}
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithDataSourceAndProperties() throws Exception {
final DriverManagerDataSource ds = new DriverManagerDataSource();
@@ -333,6 +345,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
assertTrue(invocations.contains("newSessionFactory"));
}
@Test
public void testLocalSessionFactoryBeanWithValidProperties() throws Exception {
final Set invocations = new HashSet();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@@ -354,6 +367,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
assertTrue(invocations.contains("newSessionFactory"));
}
@Test
public void testLocalSessionFactoryBeanWithInvalidProperties() throws Exception {
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
sfb.setMappingResources(new String[0]);
@@ -368,6 +382,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
}
}
@Test
public void testLocalSessionFactoryBeanWithInvalidMappings() throws Exception {
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
sfb.setMappingResources(new String[]{"mapping.hbm.xml"});
@@ -379,12 +394,9 @@ public class LocalSessionFactoryBeanTests extends TestCase {
}
}
@Test
public void testLocalSessionFactoryBeanWithCustomSessionFactory() throws Exception {
MockControl factoryControl = MockControl.createControl(SessionFactory.class);
final SessionFactory sessionFactory = (SessionFactory) factoryControl.getMock();
sessionFactory.close();
factoryControl.setVoidCallable(1);
factoryControl.replay();
final SessionFactory sessionFactory = mock(SessionFactory.class);
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected SessionFactory newSessionFactory(Configuration config) {
@@ -397,9 +409,10 @@ public class LocalSessionFactoryBeanTests extends TestCase {
sfb.afterPropertiesSet();
assertTrue(sessionFactory == sfb.getObject());
sfb.destroy();
factoryControl.verify();
verify(sessionFactory).close();
}
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithEntityInterceptor() throws Exception {
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@@ -415,9 +428,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
};
sfb.setMappingResources(new String[0]);
sfb.setDataSource(new DriverManagerDataSource());
MockControl interceptorControl = MockControl.createControl(Interceptor.class);
Interceptor entityInterceptor = (Interceptor) interceptorControl.getMock();
interceptorControl.replay();
Interceptor entityInterceptor = mock(Interceptor.class);
sfb.setEntityInterceptor(entityInterceptor);
try {
sfb.afterPropertiesSet();
@@ -429,6 +440,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
}
}
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithNamingStrategy() throws Exception {
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@@ -455,6 +467,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
}
}
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithCacheStrategies() throws Exception {
final Properties registeredClassCache = new Properties();
@@ -484,10 +497,10 @@ public class LocalSessionFactoryBeanTests extends TestCase {
sfb.setMappingResources(new String[0]);
sfb.setDataSource(new DriverManagerDataSource());
Properties classCache = new Properties();
classCache.setProperty("org.springframework.beans.TestBean", "read-write");
classCache.setProperty("org.springframework.tests.sample.beans.TestBean", "read-write");
sfb.setEntityCacheStrategies(classCache);
Properties collectionCache = new Properties();
collectionCache.setProperty("org.springframework.beans.TestBean.friends", "read-only");
collectionCache.setProperty("org.springframework.tests.sample.beans.TestBean.friends", "read-only");
sfb.setCollectionCacheStrategies(collectionCache);
sfb.afterPropertiesSet();
@@ -495,6 +508,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
assertEquals(collectionCache, registeredCollectionCache);
}
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithCacheStrategiesAndRegions() throws Exception {
final Properties registeredClassCache = new Properties();
@@ -523,10 +537,10 @@ public class LocalSessionFactoryBeanTests extends TestCase {
sfb.setMappingResources(new String[0]);
sfb.setDataSource(new DriverManagerDataSource());
Properties classCache = new Properties();
classCache.setProperty("org.springframework.beans.TestBean", "read-write,myRegion");
classCache.setProperty("org.springframework.tests.sample.beans.TestBean", "read-write,myRegion");
sfb.setEntityCacheStrategies(classCache);
Properties collectionCache = new Properties();
collectionCache.setProperty("org.springframework.beans.TestBean.friends", "read-only,myRegion");
collectionCache.setProperty("org.springframework.tests.sample.beans.TestBean.friends", "read-only,myRegion");
sfb.setCollectionCacheStrategies(collectionCache);
sfb.afterPropertiesSet();
@@ -534,6 +548,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
assertEquals(collectionCache, registeredCollectionCache);
}
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithEventListeners() throws Exception {
final Map registeredListeners = new HashMap();
@@ -562,6 +577,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
assertEquals(listeners, registeredListeners);
}
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithEventListenerSet() throws Exception {
final Map registeredListeners = new HashMap();
@@ -594,6 +610,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
}
/*
@Test
public void testLocalSessionFactoryBeanWithFilterDefinitions() throws Exception {
XmlBeanFactory xbf = new XmlBeanFactory(new ClassPathResource("filterDefinitions.xml", getClass()));
FilterTestLocalSessionFactoryBean sf = (FilterTestLocalSessionFactoryBean) xbf.getBean("&sessionFactory");
@@ -613,6 +630,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
}
*/
@Test
public void testLocalSessionFactoryBeanWithTypeDefinitions() throws Exception {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(new ClassPathResource("typeDefinitions.xml", getClass()));

View File

@@ -1,30 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBeanTests$FilterTestLocalSessionFactoryBean">
<property name="filterDefinitions">
<list>
<bean class="org.springframework.orm.hibernate3.FilterDefinitionFactoryBean">
<property name="filterName" value="filter1"/>
<property name="parameterTypes">
<props>
<prop key="param1">string</prop>
<prop key="otherParam">long</prop>
</props>
</property>
<property name="defaultFilterCondition" value="someCondition"/>
</bean>
<bean id="filter2" class="org.springframework.orm.hibernate3.FilterDefinitionFactoryBean">
<property name="parameterTypes">
<props>
<prop key="myParam">integer</prop>
</props>
</property>
</bean>
</list>
</property>
</bean>
</beans>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,25 +16,26 @@
package org.springframework.orm.hibernate3.support;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.hibernate.SessionFactory;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.orm.hibernate3.HibernateTemplate;
/**
* @author Juergen Hoeller
* @author Phillip Webb
* @since 05.03.2005
*/
public class HibernateDaoSupportTests extends TestCase {
public class HibernateDaoSupportTests {
@Test
public void testHibernateDaoSupportWithSessionFactory() throws Exception {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
sfControl.replay();
SessionFactory sf = mock(SessionFactory.class);
final List test = new ArrayList();
HibernateDaoSupport dao = new HibernateDaoSupport() {
@Override
@@ -47,9 +48,9 @@ public class HibernateDaoSupportTests extends TestCase {
assertEquals("Correct SessionFactory", sf, dao.getSessionFactory());
assertEquals("Correct HibernateTemplate", sf, dao.getHibernateTemplate().getSessionFactory());
assertEquals("initDao called", test.size(), 1);
sfControl.verify();
}
@Test
public void testHibernateDaoSupportWithHibernateTemplate() throws Exception {
HibernateTemplate template = new HibernateTemplate();
final List test = new ArrayList();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,11 @@
package org.springframework.orm.hibernate3.support;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
@@ -31,54 +36,45 @@ import javax.transaction.Status;
import javax.transaction.Synchronization;
import javax.transaction.TransactionManager;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.easymock.internal.ArrayMatcher;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.transaction.MockJtaTransaction;
import org.springframework.tests.transaction.MockJtaTransaction;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* @author Juergen Hoeller
* @author Phillip Webb
* @since 05.03.2005
*/
public class LobTypeTests extends TestCase {
public class LobTypeTests {
private MockControl rsControl = MockControl.createControl(ResultSet.class);
private ResultSet rs = (ResultSet) rsControl.getMock();
private MockControl psControl = MockControl.createControl(PreparedStatement.class);
private PreparedStatement ps = (PreparedStatement) psControl.getMock();
private ResultSet rs = mock(ResultSet.class);
private PreparedStatement ps = mock(PreparedStatement.class);
private LobHandler lobHandler = mock(LobHandler.class);
private LobCreator lobCreator = mock(LobCreator.class);
private MockControl lobHandlerControl = MockControl.createControl(LobHandler.class);
private LobHandler lobHandler = (LobHandler) lobHandlerControl.getMock();
private MockControl lobCreatorControl = MockControl.createControl(LobCreator.class);
private LobCreator lobCreator = (LobCreator) lobCreatorControl.getMock();
@Override
protected void setUp() throws SQLException {
lobHandler.getLobCreator();
lobHandlerControl.setReturnValue(lobCreator);
lobCreator.close();
lobCreatorControl.setVoidCallable(1);
rsControl.replay();
psControl.replay();
@Before
public void setUp() throws SQLException {
given(lobHandler.getLobCreator()).willReturn(lobCreator);
}
public void testClobStringType() throws Exception {
lobHandler.getClobAsString(rs, "column");
lobHandlerControl.setReturnValue("content");
lobCreator.setClobAsString(ps, 1, "content");
lobCreatorControl.setVoidCallable(1);
@After
public void tearDown() {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
verify(lobCreator).close();
}
lobHandlerControl.replay();
lobCreatorControl.replay();
@Test
public void testClobStringType() throws Exception {
given(lobHandler.getClobAsString(rs, "column")).willReturn("content");
ClobStringType type = new ClobStringType(lobHandler, null);
assertEquals(1, type.sqlTypes().length);
@@ -101,29 +97,16 @@ public class LobTypeTests extends TestCase {
finally {
TransactionSynchronizationManager.clearSynchronization();
}
verify(lobCreator).setClobAsString(ps, 1, "content");
}
@Test
public void testClobStringTypeWithSynchronizedSession() throws Exception {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
session.getSessionFactory();
sessionControl.setReturnValue(sf, 1);
session.close();
sessionControl.setReturnValue(null, 1);
sfControl.replay();
sessionControl.replay();
lobHandler.getClobAsString(rs, "column");
lobHandlerControl.setReturnValue("content");
lobCreator.setClobAsString(ps, 1, "content");
lobCreatorControl.setVoidCallable(1);
lobHandlerControl.replay();
lobCreatorControl.replay();
SessionFactory sf = mock(SessionFactory.class);
Session session = mock(Session.class);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
given(lobHandler.getClobAsString(rs, "column")).willReturn("content");
ClobStringType type = new ClobStringType(lobHandler, null);
assertEquals(1, type.sqlTypes().length);
@@ -150,18 +133,13 @@ public class LobTypeTests extends TestCase {
TransactionSynchronizationManager.clearSynchronization();
}
sfControl.verify();
sessionControl.verify();
verify(session).close();
verify(lobCreator).setClobAsString(ps, 1, "content");
}
@Test
public void testClobStringTypeWithFlushOnCommit() throws Exception {
lobHandler.getClobAsString(rs, "column");
lobHandlerControl.setReturnValue("content");
lobCreator.setClobAsString(ps, 1, "content");
lobCreatorControl.setVoidCallable(1);
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getClobAsString(rs, "column")).willReturn("content");
ClobStringType type = new ClobStringType(lobHandler, null);
assertEquals(1, type.sqlTypes().length);
@@ -182,73 +160,51 @@ public class LobTypeTests extends TestCase {
finally {
TransactionSynchronizationManager.clearSynchronization();
}
verify(lobCreator).setClobAsString(ps, 1, "content");
}
@Test
public void testClobStringTypeWithJtaSynchronization() throws Exception {
MockControl tmControl = MockControl.createControl(TransactionManager.class);
TransactionManager tm = (TransactionManager) tmControl.getMock();
TransactionManager tm = mock(TransactionManager.class);
MockJtaTransaction transaction = new MockJtaTransaction();
tm.getStatus();
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
tm.getTransaction();
tmControl.setReturnValue(transaction, 1);
given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
given(tm.getTransaction()).willReturn(transaction);
lobHandler.getClobAsString(rs, "column");
lobHandlerControl.setReturnValue("content");
lobCreator.setClobAsString(ps, 1, "content");
lobCreatorControl.setVoidCallable(1);
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getClobAsString(rs, "column")).willReturn("content");
ClobStringType type = new ClobStringType(lobHandler, tm);
assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
tmControl.replay();
type.nullSafeSet(ps, "content", 1);
Synchronization synch = transaction.getSynchronization();
assertNotNull(synch);
synch.beforeCompletion();
synch.afterCompletion(Status.STATUS_COMMITTED);
tmControl.verify();
verify(lobCreator).setClobAsString(ps, 1, "content");
}
@Test
public void testClobStringTypeWithJtaSynchronizationAndRollback() throws Exception {
MockControl tmControl = MockControl.createControl(TransactionManager.class);
TransactionManager tm = (TransactionManager) tmControl.getMock();
TransactionManager tm = mock(TransactionManager.class);
MockJtaTransaction transaction = new MockJtaTransaction();
tm.getStatus();
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
tm.getTransaction();
tmControl.setReturnValue(transaction, 1);
lobHandler.getClobAsString(rs, "column");
lobHandlerControl.setReturnValue("content");
lobCreator.setClobAsString(ps, 1, "content");
lobCreatorControl.setVoidCallable(1);
lobHandlerControl.replay();
lobCreatorControl.replay();
given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
given(tm.getTransaction()).willReturn(transaction);
given(lobHandler.getClobAsString(rs, "column")).willReturn("content");
ClobStringType type = new ClobStringType(lobHandler, tm);
assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
tmControl.replay();
type.nullSafeSet(ps, "content", 1);
Synchronization synch = transaction.getSynchronization();
assertNotNull(synch);
synch.afterCompletion(Status.STATUS_ROLLEDBACK);
tmControl.verify();
verify(lobCreator).setClobAsString(ps, 1, "content");
}
@Test
public void testBlobStringType() throws Exception {
String content = "content";
byte[] contentBytes = content.getBytes();
lobHandler.getBlobAsBytes(rs, "column");
lobHandlerControl.setReturnValue(contentBytes);
lobCreator.setBlobAsBytes(ps, 1, contentBytes);
lobCreatorControl.setMatcher(new ArrayMatcher());
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(contentBytes);
BlobStringType type = new BlobStringType(lobHandler, null);
assertEquals(1, type.sqlTypes().length);
@@ -270,15 +226,12 @@ public class LobTypeTests extends TestCase {
finally {
TransactionSynchronizationManager.clearSynchronization();
}
verify(lobCreator).setBlobAsBytes(ps, 1, contentBytes);
}
@Test
public void testBlobStringTypeWithNull() throws Exception {
lobHandler.getBlobAsBytes(rs, "column");
lobHandlerControl.setReturnValue(null);
lobCreator.setBlobAsBytes(ps, 1, null);
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(null);
BlobStringType type = new BlobStringType(lobHandler, null);
assertEquals(null, type.nullSafeGet(rs, new String[] {"column"}, null));
@@ -292,76 +245,56 @@ public class LobTypeTests extends TestCase {
finally {
TransactionSynchronizationManager.clearSynchronization();
}
verify(lobCreator).setBlobAsBytes(ps, 1, null);
}
@Test
public void testBlobStringTypeWithJtaSynchronization() throws Exception {
MockControl tmControl = MockControl.createControl(TransactionManager.class);
TransactionManager tm = (TransactionManager) tmControl.getMock();
TransactionManager tm = mock(TransactionManager.class);
MockJtaTransaction transaction = new MockJtaTransaction();
tm.getStatus();
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
tm.getTransaction();
tmControl.setReturnValue(transaction, 1);
given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
given(tm.getTransaction()).willReturn(transaction);
String content = "content";
byte[] contentBytes = content.getBytes();
lobHandler.getBlobAsBytes(rs, "column");
lobHandlerControl.setReturnValue(contentBytes);
lobCreator.setBlobAsBytes(ps, 1, contentBytes);
lobCreatorControl.setMatcher(new ArrayMatcher());
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(contentBytes);
BlobStringType type = new BlobStringType(lobHandler, tm);
assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null));
tmControl.replay();
type.nullSafeSet(ps, content, 1);
Synchronization synch = transaction.getSynchronization();
assertNotNull(synch);
synch.beforeCompletion();
synch.afterCompletion(Status.STATUS_COMMITTED);
tmControl.verify();
verify(lobCreator).setBlobAsBytes(ps, 1, contentBytes);
}
@Test
public void testBlobStringTypeWithJtaSynchronizationAndRollback() throws Exception {
MockControl tmControl = MockControl.createControl(TransactionManager.class);
TransactionManager tm = (TransactionManager) tmControl.getMock();
TransactionManager tm = mock(TransactionManager.class);
MockJtaTransaction transaction = new MockJtaTransaction();
tm.getStatus();
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
tm.getTransaction();
tmControl.setReturnValue(transaction, 1);
given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
given(tm.getTransaction()).willReturn(transaction);
String content = "content";
byte[] contentBytes = content.getBytes();
lobHandler.getBlobAsBytes(rs, "column");
lobHandlerControl.setReturnValue(contentBytes);
lobCreator.setBlobAsBytes(ps, 1, contentBytes);
lobCreatorControl.setMatcher(new ArrayMatcher());
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(contentBytes);
BlobStringType type = new BlobStringType(lobHandler, tm);
assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null));
tmControl.replay();
type.nullSafeSet(ps, content, 1);
Synchronization synch = transaction.getSynchronization();
assertNotNull(synch);
synch.afterCompletion(Status.STATUS_ROLLEDBACK);
tmControl.verify();
verify(lobCreator).setBlobAsBytes(ps, 1, contentBytes);
}
@Test
public void testBlobByteArrayType() throws Exception {
byte[] content = "content".getBytes();
lobHandler.getBlobAsBytes(rs, "column");
lobHandlerControl.setReturnValue(content);
lobCreator.setBlobAsBytes(ps, 1, content);
lobCreatorControl.setVoidCallable(1);
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(content);
BlobByteArrayType type = new BlobByteArrayType(lobHandler, null);
assertEquals(1, type.sqlTypes().length);
@@ -383,78 +316,56 @@ public class LobTypeTests extends TestCase {
finally {
TransactionSynchronizationManager.clearSynchronization();
}
verify(lobCreator).setBlobAsBytes(ps, 1, content);
}
@Test
public void testBlobByteArrayTypeWithJtaSynchronization() throws Exception {
MockControl tmControl = MockControl.createControl(TransactionManager.class);
TransactionManager tm = (TransactionManager) tmControl.getMock();
TransactionManager tm = mock(TransactionManager.class);
MockJtaTransaction transaction = new MockJtaTransaction();
tm.getStatus();
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
tm.getTransaction();
tmControl.setReturnValue(transaction, 1);
given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
given(tm.getTransaction()).willReturn(transaction);
byte[] content = "content".getBytes();
lobHandler.getBlobAsBytes(rs, "column");
lobHandlerControl.setReturnValue(content);
lobCreator.setBlobAsBytes(ps, 1, content);
lobCreatorControl.setVoidCallable(1);
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(content);
BlobByteArrayType type = new BlobByteArrayType(lobHandler, tm);
assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null));
tmControl.replay();
type.nullSafeSet(ps, content, 1);
Synchronization synch = transaction.getSynchronization();
assertNotNull(synch);
synch.beforeCompletion();
synch.afterCompletion(Status.STATUS_COMMITTED);
tmControl.verify();
verify(lobCreator).setBlobAsBytes(ps, 1, content);
}
@Test
public void testBlobByteArrayTypeWithJtaSynchronizationAndRollback() throws Exception {
MockControl tmControl = MockControl.createControl(TransactionManager.class);
TransactionManager tm = (TransactionManager) tmControl.getMock();
TransactionManager tm = mock(TransactionManager.class);
MockJtaTransaction transaction = new MockJtaTransaction();
tm.getStatus();
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
tm.getTransaction();
tmControl.setReturnValue(transaction, 1);
given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
given(tm.getTransaction()).willReturn(transaction);
byte[] content = "content".getBytes();
lobHandler.getBlobAsBytes(rs, "column");
lobHandlerControl.setReturnValue(content);
lobCreator.setBlobAsBytes(ps, 1, content);
lobCreatorControl.setVoidCallable(1);
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(content);
BlobByteArrayType type = new BlobByteArrayType(lobHandler, tm);
assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null));
tmControl.replay();
type.nullSafeSet(ps, content, 1);
Synchronization synch = transaction.getSynchronization();
assertNotNull(synch);
synch.afterCompletion(Status.STATUS_ROLLEDBACK);
tmControl.verify();
verify(lobCreator).setBlobAsBytes(ps, 1, content);
}
@Test
public void testBlobSerializableType() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject("content");
oos.close();
lobHandler.getBlobAsBinaryStream(rs, "column");
lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray()));
lobCreator.setBlobAsBytes(ps, 1, baos.toByteArray());
lobCreatorControl.setMatcher(new ArrayMatcher());
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getBlobAsBinaryStream(rs, "column")).willReturn(new ByteArrayInputStream(baos.toByteArray()));
BlobSerializableType type = new BlobSerializableType(lobHandler, null);
assertEquals(1, type.sqlTypes().length);
@@ -474,15 +385,12 @@ public class LobTypeTests extends TestCase {
finally {
TransactionSynchronizationManager.clearSynchronization();
}
verify(lobCreator).setBlobAsBytes(ps, 1, baos.toByteArray());
}
@Test
public void testBlobSerializableTypeWithNull() throws Exception {
lobHandler.getBlobAsBinaryStream(rs, "column");
lobHandlerControl.setReturnValue(null);
lobCreator.setBlobAsBytes(ps, 1, null);
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getBlobAsBinaryStream(rs, "column")).willReturn(null);
BlobSerializableType type = new BlobSerializableType(lobHandler, null);
assertEquals(null, type.nullSafeGet(rs, new String[] {"column"}, null));
@@ -496,29 +404,23 @@ public class LobTypeTests extends TestCase {
finally {
TransactionSynchronizationManager.clearSynchronization();
}
verify(lobCreator).setBlobAsBytes(ps, 1, null);
}
@Test
public void testBlobSerializableTypeWithJtaSynchronization() throws Exception {
MockControl tmControl = MockControl.createControl(TransactionManager.class);
TransactionManager tm = (TransactionManager) tmControl.getMock();
TransactionManager tm = mock(TransactionManager.class);
MockJtaTransaction transaction = new MockJtaTransaction();
tm.getStatus();
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
tm.getTransaction();
tmControl.setReturnValue(transaction, 1);
given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
given(tm.getTransaction()).willReturn(transaction);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject("content");
oos.close();
lobHandler.getBlobAsBinaryStream(rs, "column");
lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray()));
lobCreator.setBlobAsBytes(ps, 1, baos.toByteArray());
lobCreatorControl.setMatcher(new ArrayMatcher());
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getBlobAsBinaryStream(rs, "column")).willReturn(
new ByteArrayInputStream(baos.toByteArray()));
BlobSerializableType type = new BlobSerializableType(lobHandler, tm);
assertEquals(1, type.sqlTypes().length);
@@ -527,36 +429,28 @@ public class LobTypeTests extends TestCase {
assertTrue(type.isMutable());
assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
tmControl.replay();
type.nullSafeSet(ps, "content", 1);
Synchronization synch = transaction.getSynchronization();
assertNotNull(synch);
synch.beforeCompletion();
synch.afterCompletion(Status.STATUS_COMMITTED);
tmControl.verify();
verify(lobCreator).setBlobAsBytes(ps, 1, baos.toByteArray());
}
@Test
public void testBlobSerializableTypeWithJtaSynchronizationAndRollback() throws Exception {
MockControl tmControl = MockControl.createControl(TransactionManager.class);
TransactionManager tm = (TransactionManager) tmControl.getMock();
TransactionManager tm = mock(TransactionManager.class);
MockJtaTransaction transaction = new MockJtaTransaction();
tm.getStatus();
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
tm.getTransaction();
tmControl.setReturnValue(transaction, 1);
given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
given(tm.getTransaction()).willReturn(transaction);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject("content");
oos.close();
lobHandler.getBlobAsBinaryStream(rs, "column");
lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray()));
lobCreator.setBlobAsBytes(ps, 1, baos.toByteArray());
lobCreatorControl.setMatcher(new ArrayMatcher());
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getBlobAsBinaryStream(rs, "column")).willReturn(
new ByteArrayInputStream(baos.toByteArray()));
BlobSerializableType type = new BlobSerializableType(lobHandler, tm);
assertEquals(1, type.sqlTypes().length);
@@ -565,20 +459,15 @@ public class LobTypeTests extends TestCase {
assertTrue(type.isMutable());
assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
tmControl.replay();
type.nullSafeSet(ps, "content", 1);
Synchronization synch = transaction.getSynchronization();
assertNotNull(synch);
synch.afterCompletion(Status.STATUS_ROLLEDBACK);
tmControl.verify();
verify(lobCreator).setBlobAsBytes(ps, 1, baos.toByteArray());
}
@Test
public void testHbm2JavaStyleInitialization() throws Exception {
rsControl.reset();
psControl.reset();
lobHandlerControl.reset();
lobCreatorControl.reset();
ClobStringType cst = null;
BlobByteArrayType bbat = null;
BlobSerializableType bst = null;
@@ -612,21 +501,6 @@ public class LobTypeTests extends TestCase {
catch (IllegalStateException ex) {
// expected
}
lobCreator.close();
}
@Override
protected void tearDown() {
try {
rsControl.verify();
psControl.verify();
lobHandlerControl.verify();
lobCreatorControl.verify();
}
catch (IllegalStateException ex) {
// ignore: test method didn't call replay
}
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,11 +16,15 @@
package org.springframework.orm.hibernate3.support;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.io.IOException;
import java.sql.Connection;
@@ -33,9 +37,7 @@ import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.transaction.TransactionManager;
import org.easymock.EasyMock;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
@@ -66,6 +68,7 @@ import org.springframework.web.context.support.StaticWebApplicationContext;
/**
* @author Juergen Hoeller
* @author Rossen Stoyanchev
* @author Phillip Webb
* @since 05.03.2005
*/
public class OpenSessionInViewTests {
@@ -90,19 +93,16 @@ public class OpenSessionInViewTests {
@Test
public void testOpenSessionInViewInterceptorWithSingleSession() throws Exception {
SessionFactory sf = createStrictMock(SessionFactory.class);
Session session = createStrictMock(Session.class);
SessionFactory sf = mock(SessionFactory.class);
Session session = mock(Session.class);
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
interceptor.setSessionFactory(sf);
expect(sf.openSession()).andReturn(session);
expect(session.getSessionFactory()).andReturn(sf);
session.setFlushMode(FlushMode.MANUAL);
expect(session.getSessionFactory()).andReturn(sf);
expect(session.isOpen()).andReturn(true);
replay(sf);
replay(session);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
given(session.getSessionFactory()).willReturn(sf);
given(session.isOpen()).willReturn(true);
interceptor.preHandle(this.webRequest);
assertTrue(TransactionSynchronizationManager.hasResource(sf));
@@ -122,29 +122,14 @@ public class OpenSessionInViewTests {
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
verify(sf);
verify(session);
reset(sf);
reset(session);
replay(sf);
replay(session);
interceptor.postHandle(this.webRequest, null);
assertTrue(TransactionSynchronizationManager.hasResource(sf));
verify(sf);
verify(session);
reset(sf);
reset(session);
expect(session.close()).andReturn(null);
replay(sf);
replay(session);
interceptor.afterCompletion(this.webRequest, null);
assertFalse(TransactionSynchronizationManager.hasResource(sf));
verify(sf);
verify(session);
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session).close();
}
@Test
@@ -152,30 +137,19 @@ public class OpenSessionInViewTests {
// Initial request thread
final SessionFactory sf = createStrictMock(SessionFactory.class);
Session session = createStrictMock(Session.class);
final SessionFactory sf = mock(SessionFactory.class);
Session session = mock(Session.class);
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
interceptor.setSessionFactory(sf);
expect(sf.openSession()).andReturn(session);
expect(session.getSessionFactory()).andReturn(sf);
session.setFlushMode(FlushMode.MANUAL);
replay(sf);
replay(session);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
interceptor.preHandle(this.webRequest);
assertTrue(TransactionSynchronizationManager.hasResource(sf));
verify(sf);
verify(session);
AsyncWebRequest asyncWebRequest = createStrictMock(AsyncWebRequest.class);
asyncWebRequest.addCompletionHandler((Runnable) anyObject());
asyncWebRequest.addTimeoutHandler((Runnable) anyObject());
asyncWebRequest.addCompletionHandler((Runnable) anyObject());
asyncWebRequest.startAsync();
replay(asyncWebRequest);
AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class);
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request);
asyncManager.setTaskExecutor(new SyncTaskExecutor());
@@ -188,8 +162,6 @@ public class OpenSessionInViewTests {
}
});
verify(asyncWebRequest);
interceptor.afterConcurrentHandlingStarted(this.webRequest);
assertFalse(TransactionSynchronizationManager.hasResource(sf));
@@ -198,56 +170,34 @@ public class OpenSessionInViewTests {
interceptor.preHandle(this.webRequest);
assertTrue("Session not bound to async thread", TransactionSynchronizationManager.hasResource(sf));
verify(sf);
reset(sf);
replay(sf);
verify(session);
reset(session);
replay(session);
interceptor.postHandle(this.webRequest, null);
assertTrue(TransactionSynchronizationManager.hasResource(sf));
verify(sf);
reset(sf);
verify(session);
reset(session);
expect(session.close()).andReturn(null);
replay(sf);
replay(session);
interceptor.afterCompletion(this.webRequest, null);
assertFalse(TransactionSynchronizationManager.hasResource(sf));
verify(sf);
verify(session);
verify(session).setFlushMode(FlushMode.MANUAL);
verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class));
verify(asyncWebRequest).startAsync();
}
@Test
public void testOpenSessionInViewInterceptorWithSingleSessionAndJtaTm() throws Exception {
final SessionFactoryImplementor sf = createStrictMock(SessionFactoryImplementor.class);
Session session = createStrictMock(Session.class);
final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class);
Session session = mock(Session.class);
TransactionManager tm = createStrictMock(TransactionManager.class);
expect(tm.getTransaction()).andReturn(null);
expect(tm.getTransaction()).andReturn(null);
replay(tm);
TransactionManager tm = mock(TransactionManager.class);
given(tm.getTransaction()).willReturn(null);
given(tm.getTransaction()).willReturn(null);
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
interceptor.setSessionFactory(sf);
expect(sf.openSession()).andReturn(session);
expect(sf.getTransactionManager()).andReturn(tm);
session.setFlushMode(FlushMode.MANUAL);
expect(sf.getTransactionManager()).andReturn(tm);
expect(session.isOpen()).andReturn(true);
replay(sf);
replay(session);
given(sf.openSession()).willReturn(session);
given(sf.getTransactionManager()).willReturn(tm);
given(sf.getTransactionManager()).willReturn(tm);
given(session.isOpen()).willReturn(true);
interceptor.preHandle(this.webRequest);
assertTrue(TransactionSynchronizationManager.hasResource(sf));
@@ -268,86 +218,50 @@ public class OpenSessionInViewTests {
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
verify(sf);
verify(session);
reset(sf);
reset(session);
replay(sf);
replay(session);
interceptor.postHandle(this.webRequest, null);
assertTrue(TransactionSynchronizationManager.hasResource(sf));
verify(sf);
verify(session);
reset(sf);
reset(session);
expect(session.close()).andReturn(null);
replay(sf);
replay(session);
interceptor.afterCompletion(this.webRequest, null);
assertFalse(TransactionSynchronizationManager.hasResource(sf));
verify(sf);
verify(session);
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session).close();
}
@Test
public void testOpenSessionInViewInterceptorWithSingleSessionAndFlush() throws Exception {
SessionFactory sf = createStrictMock(SessionFactory.class);
Session session = createStrictMock(Session.class);
SessionFactory sf = mock(SessionFactory.class);
Session session = mock(Session.class);
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setFlushMode(HibernateAccessor.FLUSH_AUTO);
expect(sf.openSession()).andReturn(session);
expect(session.getSessionFactory()).andReturn(sf);
replay(sf);
replay(session);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
interceptor.preHandle(this.webRequest);
assertTrue(TransactionSynchronizationManager.hasResource(sf));
verify(sf);
verify(session);
reset(sf);
reset(session);
session.flush();
replay(sf);
replay(session);
interceptor.postHandle(this.webRequest, null);
assertTrue(TransactionSynchronizationManager.hasResource(sf));
verify(sf);
verify(session);
reset(sf);
reset(session);
expect(session.close()).andReturn(null);
replay(sf);
replay(session);
interceptor.afterCompletion(this.webRequest, null);
assertFalse(TransactionSynchronizationManager.hasResource(sf));
verify(sf);
verify(session);
verify(session).flush();
verify(session).close();
}
@Test
public void testOpenSessionInViewInterceptorAndDeferredClose() throws Exception {
SessionFactory sf = createStrictMock(SessionFactory.class);
Session session = createStrictMock(Session.class);
SessionFactory sf = mock(SessionFactory.class);
Session session = mock(Session.class);
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
interceptor.setSessionFactory(sf);
interceptor.setSingleSession(false);
expect(sf.openSession()).andReturn(session);
expect(session.getSessionFactory()).andReturn(sf);
session.setFlushMode(FlushMode.MANUAL);
replay(sf);
replay(session);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
interceptor.preHandle(this.webRequest);
org.hibernate.Session sess = SessionFactoryUtils.getSession(sf, true);
@@ -367,43 +281,28 @@ public class OpenSessionInViewTests {
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
verify(sf);
verify(session);
reset(sf);
reset(session);
expect(session.close()).andReturn(null);
replay(sf);
replay(session);
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
verify(sf);
verify(session);
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session).close();
}
@Test
public void testOpenSessionInViewFilterWithSingleSession() throws Exception {
final SessionFactory sf = createStrictMock(SessionFactory.class);
Session session = createStrictMock(Session.class);
final SessionFactory sf = mock(SessionFactory.class);
Session session = mock(Session.class);
expect(sf.openSession()).andReturn(session);
expect(session.getSessionFactory()).andReturn(sf);
session.setFlushMode(FlushMode.MANUAL);
expect(session.close()).andReturn(null);
replay(sf);
replay(session);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
given(session.close()).willReturn(null);
final SessionFactory sf2 = createStrictMock(SessionFactory.class);
Session session2 = createStrictMock(Session.class);
final SessionFactory sf2 = mock(SessionFactory.class);
Session session2 = mock(Session.class);
expect(sf2.openSession()).andReturn(session2);
expect(session2.getSessionFactory()).andReturn(sf2);
session2.setFlushMode(FlushMode.AUTO);
expect(session2.close()).andReturn(null);
replay(sf2);
replay(session2);
given(sf2.openSession()).willReturn(session2);
given(session2.getSessionFactory()).willReturn(sf2);
given(session2.close()).willReturn(null);
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
@@ -448,26 +347,20 @@ public class OpenSessionInViewTests {
assertFalse(TransactionSynchronizationManager.hasResource(sf2));
assertNotNull(this.request.getAttribute("invoked"));
verify(sf);
verify(session);
verify(sf2);
verify(session2);
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session2).setFlushMode(FlushMode.AUTO);
wac.close();
}
@Test
public void testOpenSessionInViewFilterAsyncScenario() throws Exception {
final SessionFactory sf = createStrictMock(SessionFactory.class);
Session session = createStrictMock(Session.class);
final SessionFactory sf = mock(SessionFactory.class);
Session session = mock(Session.class);
// Initial request during which concurrent handling starts..
expect(sf.openSession()).andReturn(session);
expect(session.getSessionFactory()).andReturn(sf);
session.setFlushMode(FlushMode.MANUAL);
replay(sf);
replay(session);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
@@ -490,13 +383,8 @@ public class OpenSessionInViewTests {
}
};
AsyncWebRequest asyncWebRequest = createMock(AsyncWebRequest.class);
asyncWebRequest.addCompletionHandler((Runnable) anyObject());
asyncWebRequest.addTimeoutHandler(EasyMock.<Runnable>anyObject());
asyncWebRequest.addCompletionHandler((Runnable) anyObject());
asyncWebRequest.startAsync();
expect(asyncWebRequest.isAsyncStarted()).andReturn(true).anyTimes();
replay(asyncWebRequest);
AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class);
given(asyncWebRequest.isAsyncStarted()).willReturn(true);
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request);
asyncManager.setTaskExecutor(new SyncTaskExecutor());
@@ -513,46 +401,29 @@ public class OpenSessionInViewTests {
assertFalse(TransactionSynchronizationManager.hasResource(sf));
assertEquals(1, count.get());
verify(sf);
verify(session);
verify(asyncWebRequest);
reset(sf);
reset(session);
reset(asyncWebRequest);
// Async dispatch after concurrent handling produces result ...
expect(session.close()).andReturn(null);
expect(asyncWebRequest.isAsyncStarted()).andReturn(false).anyTimes();
replay(sf);
replay(session);
replay(asyncWebRequest);
assertFalse(TransactionSynchronizationManager.hasResource(sf));
filter.doFilter(this.request, this.response, filterChain);
assertFalse(TransactionSynchronizationManager.hasResource(sf));
assertEquals(2, count.get());
verify(sf);
verify(session);
verify(asyncWebRequest);
verify(session).setFlushMode(FlushMode.MANUAL);
verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class));
verify(asyncWebRequest).startAsync();
wac.close();
}
@Test
public void testOpenSessionInViewFilterWithSingleSessionAndPreBoundSession() throws Exception {
final SessionFactory sf = createStrictMock(SessionFactory.class);
Session session = createStrictMock(Session.class);
final SessionFactory sf = mock(SessionFactory.class);
Session session = mock(Session.class);
expect(sf.openSession()).andReturn(session);
expect(session.getSessionFactory()).andReturn(sf);
session.setFlushMode(FlushMode.MANUAL);
expect(session.close()).andReturn(null);
replay(sf);
replay(session);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
@@ -588,43 +459,32 @@ public class OpenSessionInViewTests {
interceptor.postHandle(this.webRequest, null);
interceptor.afterCompletion(this.webRequest, null);
verify(sf);
verify(session);
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session).close();
wac.close();
}
@Test
public void testOpenSessionInViewFilterWithDeferredClose() throws Exception {
final SessionFactory sf = createStrictMock(SessionFactory.class);
final Session session = createStrictMock(Session.class);
final SessionFactory sf = mock(SessionFactory.class);
final Session session = mock(Session.class);
expect(sf.openSession()).andReturn(session);
expect(session.getSessionFactory()).andReturn(sf);
expect(session.getFlushMode()).andReturn(FlushMode.MANUAL);
session.setFlushMode(FlushMode.MANUAL);
replay(sf);
replay(session);
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
given(session.getFlushMode()).willReturn(FlushMode.MANUAL);
final SessionFactory sf2 = createStrictMock(SessionFactory.class);
final Session session2 = createStrictMock(Session.class);
final SessionFactory sf2 = mock(SessionFactory.class);
final Session session2 = mock(Session.class);
Transaction tx = createStrictMock(Transaction.class);
Connection con = createStrictMock(Connection.class);
Transaction tx = mock(Transaction.class);
Connection con = mock(Connection.class);
expect(sf2.openSession()).andReturn(session2);
expect(session2.connection()).andReturn(con);
expect(session2.beginTransaction()).andReturn(tx);
expect(session2.isConnected()).andReturn(true);
expect(session2.connection()).andReturn(con);
tx.commit();
expect(con.isReadOnly()).andReturn(false);
session2.setFlushMode(FlushMode.MANUAL);
replay(sf2);
replay(session2);
replay(tx);
replay(con);
given(sf2.openSession()).willReturn(session2);
given(session2.connection()).willReturn(con);
given(session2.beginTransaction()).willReturn(tx);
given(session2.isConnected()).willReturn(true);
given(session2.connection()).willReturn(con);
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
@@ -653,13 +513,6 @@ public class OpenSessionInViewTests {
org.hibernate.Session sess = SessionFactoryUtils.getSession(sf, true);
SessionFactoryUtils.releaseSession(sess, sf);
tm.commit(ts);
verify(session);
reset(session);
expect(session.close()).andReturn(null);
replay(session);
servletRequest.setAttribute("invoked", Boolean.TRUE);
}
};
@@ -668,17 +521,9 @@ public class OpenSessionInViewTests {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
HibernateTransactionManager tm = new HibernateTransactionManager(sf2);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
tm.commit(ts);
verify(session2);
reset(session2);
expect(session2.close()).andReturn(null);
replay(session2);
filter.doFilter(servletRequest, servletResponse, filterChain);
}
};
@@ -688,39 +533,23 @@ public class OpenSessionInViewTests {
filter2.doFilter(this.request, this.response, filterChain3);
assertNotNull(this.request.getAttribute("invoked"));
verify(sf);
verify(session);
verify(sf2);
verify(session2);
verify(tx);
verify(con);
verify(session).setFlushMode(FlushMode.MANUAL);
verify(tx).commit();
verify(session2).setFlushMode(FlushMode.MANUAL);
verify(session).close();
verify(session2).close();
wac.close();
}
@Test
public void testOpenSessionInViewFilterWithDeferredCloseAndAlreadyActiveDeferredClose() throws Exception {
final SessionFactory sf = createStrictMock(SessionFactory.class);
final Session session = createStrictMock(Session.class);
final SessionFactory sf = mock(SessionFactory.class);
final Session session = mock(Session.class);
expect(sf.openSession()).andReturn(session);
expect(session.getSessionFactory()).andReturn(sf);
expect(session.getFlushMode()).andReturn(FlushMode.MANUAL);
session.setFlushMode(FlushMode.MANUAL);
replay(sf);
replay(session);
// sf.openSession();
// sfControl.setReturnValue(session, 1);
// session.getSessionFactory();
// sessionControl.setReturnValue(sf);
// session.getFlushMode();
// sessionControl.setReturnValue(FlushMode.MANUAL, 1);
// session.setFlushMode(FlushMode.MANUAL);
// sessionControl.setVoidCallable(1);
// sfControl.replay();
// sessionControl.replay();
given(sf.openSession()).willReturn(session);
given(session.getSessionFactory()).willReturn(sf);
given(session.getFlushMode()).willReturn(FlushMode.MANUAL);
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
@@ -754,16 +583,6 @@ public class OpenSessionInViewTests {
org.hibernate.Session sess = SessionFactoryUtils.getSession(sf, true);
SessionFactoryUtils.releaseSession(sess, sf);
tm.commit(ts);
verify(session);
reset(session);
try {
expect(session.close()).andReturn(null);
}
catch (HibernateException ex) {
}
replay(session);
servletRequest.setAttribute("invoked", Boolean.TRUE);
}
};
@@ -782,8 +601,8 @@ public class OpenSessionInViewTests {
interceptor.postHandle(webRequest, null);
interceptor.afterCompletion(webRequest, null);
verify(sf);
verify(session);
verify(session).setFlushMode(FlushMode.MANUAL);
verify(session).close();
wac.close();
}

View File

@@ -1,32 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBeanTests$TypeTestLocalSessionFactoryBean">
<property name="typeDefinitions">
<list>
<bean class="org.springframework.orm.hibernate3.TypeDefinitionBean">
<property name="typeName" value="type1"/>
<property name="typeClass" value="mypackage.MyTypeClass"/>
<property name="parameters">
<props>
<prop key="param1">value1</prop>
<prop key="otherParam">othervalue</prop>
</props>
</property>
</bean>
<bean id="type2" class="org.springframework.orm.hibernate3.TypeDefinitionBean">
<property name="typeName" value="type2"/>
<property name="typeClass" value="mypackage.MyOtherTypeClass"/>
<property name="parameters">
<props>
<prop key="myParam">myvalue</prop>
</props>
</property>
</bean>
</list>
</property>
</bean>
</beans>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,13 @@
package org.springframework.orm.ibatis;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
@@ -25,24 +32,25 @@ import java.util.Map;
import javax.sql.DataSource;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapExecutor;
import com.ibatis.sqlmap.client.SqlMapSession;
import com.ibatis.sqlmap.client.event.RowHandler;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapExecutor;
import com.ibatis.sqlmap.client.SqlMapSession;
import com.ibatis.sqlmap.client.event.RowHandler;
/**
* @author Juergen Hoeller
* @author Alef Arendsen
* @author Phillip Webb
* @since 09.10.2004
*/
public class SqlMapClientTests extends TestCase {
public class SqlMapClientTests {
@Test
public void testSqlMapClientFactoryBeanWithoutConfig() throws Exception {
SqlMapClientFactoryBean factory = new SqlMapClientFactoryBean();
// explicitly set to null, don't know why ;-)
@@ -56,32 +64,15 @@ public class SqlMapClientTests extends TestCase {
}
}
@Test
public void testSqlMapClientTemplate() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
ds.getConnection();
dsControl.setReturnValue(con, 1);
con.close();
conControl.setVoidCallable(1);
dsControl.replay();
conControl.replay();
DataSource ds = mock(DataSource.class);
Connection con = mock(Connection.class);
final SqlMapSession session = mock(SqlMapSession.class);
SqlMapClient client = mock(SqlMapClient.class);
MockControl sessionControl = MockControl.createControl(SqlMapSession.class);
final SqlMapSession session = (SqlMapSession) sessionControl.getMock();
MockControl clientControl = MockControl.createControl(SqlMapClient.class);
SqlMapClient client = (SqlMapClient) clientControl.getMock();
client.openSession();
clientControl.setReturnValue(session, 1);
session.getCurrentConnection();
sessionControl.setReturnValue(null, 1);
session.setUserConnection(con);
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
sessionControl.replay();
clientControl.replay();
given(ds.getConnection()).willReturn(con);
given(client.openSession()).willReturn(session);
SqlMapClientTemplate template = new SqlMapClientTemplate();
template.setDataSource(ds);
@@ -95,30 +86,21 @@ public class SqlMapClientTests extends TestCase {
}
});
assertEquals("done", result);
dsControl.verify();
conControl.verify();
sessionControl.verify();
clientControl.verify();
verify(con).close();
verify(session).setUserConnection(con);
verify(session).close();
}
@Test
public void testSqlMapClientTemplateWithNestedSqlMapSession() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
final Connection con = (Connection) conControl.getMock();
dsControl.replay();
conControl.replay();
DataSource ds = mock(DataSource.class);
final Connection con = mock(Connection.class);
final SqlMapSession session = mock(SqlMapSession.class);
SqlMapClient client = mock(SqlMapClient.class);
MockControl sessionControl = MockControl.createControl(SqlMapSession.class);
final SqlMapSession session = (SqlMapSession) sessionControl.getMock();
MockControl clientControl = MockControl.createControl(SqlMapClient.class);
SqlMapClient client = (SqlMapClient) clientControl.getMock();
client.openSession();
clientControl.setReturnValue(session, 1);
session.getCurrentConnection();
sessionControl.setReturnValue(con, 1);
sessionControl.replay();
clientControl.replay();
given(client.openSession()).willReturn(session);
given(session.getCurrentConnection()).willReturn(con);
SqlMapClientTemplate template = new SqlMapClientTemplate();
template.setDataSource(ds);
@@ -132,210 +114,157 @@ public class SqlMapClientTests extends TestCase {
}
});
assertEquals("done", result);
dsControl.verify();
conControl.verify();
sessionControl.verify();
clientControl.verify();
}
@Test
public void testQueryForObjectOnSqlMapSession() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl clientControl = MockControl.createControl(SqlMapClient.class);
SqlMapClient client = (SqlMapClient) clientControl.getMock();
MockControl sessionControl = MockControl.createControl(SqlMapSession.class);
SqlMapSession session = (SqlMapSession) sessionControl.getMock();
DataSource ds = mock(DataSource.class);
Connection con = mock(Connection.class);
SqlMapClient client = mock(SqlMapClient.class);
SqlMapSession session = mock(SqlMapSession.class);
ds.getConnection();
dsControl.setReturnValue(con, 1);
con.close();
conControl.setVoidCallable(1);
client.getDataSource();
clientControl.setReturnValue(ds, 2);
client.openSession();
clientControl.setReturnValue(session, 1);
session.getCurrentConnection();
sessionControl.setReturnValue(null, 1);
session.setUserConnection(con);
sessionControl.setVoidCallable(1);
session.queryForObject("myStatement", "myParameter");
sessionControl.setReturnValue("myResult", 1);
session.close();
sessionControl.setVoidCallable(1);
dsControl.replay();
conControl.replay();
clientControl.replay();
sessionControl.replay();
given(ds.getConnection()).willReturn(con);
given(client.getDataSource()).willReturn(ds);
given(client.openSession()).willReturn(session);
given(session.queryForObject("myStatement", "myParameter")).willReturn("myResult");
SqlMapClientTemplate template = new SqlMapClientTemplate();
template.setSqlMapClient(client);
template.afterPropertiesSet();
assertEquals("myResult", template.queryForObject("myStatement", "myParameter"));
dsControl.verify();
clientControl.verify();
verify(con).close();
verify(session).setUserConnection(con);
verify(session).close();
}
@Test
public void testQueryForObject() throws SQLException {
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.queryForObject("myStatement", null);
template.executorControl.setReturnValue("myResult", 1);
template.executorControl.replay();
given(template.executor.queryForObject("myStatement", null)).willReturn("myResult");
assertEquals("myResult", template.queryForObject("myStatement"));
template.executorControl.verify();
}
@Test
public void testQueryForObjectWithParameter() throws SQLException {
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.queryForObject("myStatement", "myParameter");
template.executorControl.setReturnValue("myResult", 1);
template.executorControl.replay();
given(template.executor.queryForObject("myStatement", "myParameter")).willReturn("myResult");
assertEquals("myResult", template.queryForObject("myStatement", "myParameter"));
template.executorControl.verify();
}
@Test
public void testQueryForObjectWithParameterAndResultObject() throws SQLException {
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.queryForObject("myStatement", "myParameter", "myResult");
template.executorControl.setReturnValue("myResult", 1);
template.executorControl.replay();
given(template.executor.queryForObject("myStatement", "myParameter",
"myResult")).willReturn("myResult");
assertEquals("myResult", template.queryForObject("myStatement", "myParameter", "myResult"));
template.executorControl.verify();
}
@Test
public void testQueryForList() throws SQLException {
List result = new ArrayList();
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.queryForList("myStatement", null);
template.executorControl.setReturnValue(result, 1);
template.executorControl.replay();
given(template.executor.queryForList("myStatement", null)).willReturn(result);
assertEquals(result, template.queryForList("myStatement"));
template.executorControl.verify();
}
@Test
public void testQueryForListWithParameter() throws SQLException {
List result = new ArrayList();
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.queryForList("myStatement", "myParameter");
template.executorControl.setReturnValue(result, 1);
template.executorControl.replay();
given(template.executor.queryForList("myStatement", "myParameter")).willReturn(result);
assertEquals(result, template.queryForList("myStatement", "myParameter"));
template.executorControl.verify();
}
@Test
public void testQueryForListWithResultSize() throws SQLException {
List result = new ArrayList();
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.queryForList("myStatement", null, 10, 20);
template.executorControl.setReturnValue(result, 1);
template.executorControl.replay();
given(template.executor.queryForList("myStatement", null, 10, 20)).willReturn(result);
assertEquals(result, template.queryForList("myStatement", 10, 20));
template.executorControl.verify();
}
@Test
public void testQueryForListParameterAndWithResultSize() throws SQLException {
List result = new ArrayList();
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.queryForList("myStatement", "myParameter", 10, 20);
template.executorControl.setReturnValue(result, 1);
template.executorControl.replay();
given(template.executor.queryForList("myStatement", "myParameter", 10, 20)).willReturn(result);
assertEquals(result, template.queryForList("myStatement", "myParameter", 10, 20));
template.executorControl.verify();
}
@Test
public void testQueryWithRowHandler() throws SQLException {
RowHandler rowHandler = new TestRowHandler();
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.queryWithRowHandler("myStatement", null, rowHandler);
template.executorControl.setVoidCallable(1);
template.executorControl.replay();
template.queryWithRowHandler("myStatement", rowHandler);
template.executorControl.verify();
verify(template.executor).queryWithRowHandler("myStatement", null, rowHandler);
}
@Test
public void testQueryWithRowHandlerWithParameter() throws SQLException {
RowHandler rowHandler = new TestRowHandler();
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.queryWithRowHandler("myStatement", "myParameter", rowHandler);
template.executorControl.setVoidCallable(1);
template.executorControl.replay();
template.queryWithRowHandler("myStatement", "myParameter", rowHandler);
template.executorControl.verify();
verify(template.executor).queryWithRowHandler("myStatement", "myParameter", rowHandler);
}
@Test
public void testQueryForMap() throws SQLException {
Map result = new HashMap();
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.queryForMap("myStatement", "myParameter", "myKey");
template.executorControl.setReturnValue(result, 1);
template.executorControl.replay();
given(template.executor.queryForMap("myStatement", "myParameter", "myKey")).willReturn(result);
assertEquals(result, template.queryForMap("myStatement", "myParameter", "myKey"));
template.executorControl.verify();
}
@Test
public void testQueryForMapWithValueProperty() throws SQLException {
Map result = new HashMap();
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.queryForMap("myStatement", "myParameter", "myKey", "myValue");
template.executorControl.setReturnValue(result, 1);
template.executorControl.replay();
given(template.executor.queryForMap("myStatement", "myParameter", "myKey",
"myValue")).willReturn(result);
assertEquals(result, template.queryForMap("myStatement", "myParameter", "myKey", "myValue"));
template.executorControl.verify();
}
@Test
public void testInsert() throws SQLException {
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.insert("myStatement", null);
template.executorControl.setReturnValue("myResult", 1);
template.executorControl.replay();
given(template.executor.insert("myStatement", null)).willReturn("myResult");
assertEquals("myResult", template.insert("myStatement"));
template.executorControl.verify();
}
@Test
public void testInsertWithParameter() throws SQLException {
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.insert("myStatement", "myParameter");
template.executorControl.setReturnValue("myResult", 1);
template.executorControl.replay();
given(template.executor.insert("myStatement", "myParameter")).willReturn("myResult");
assertEquals("myResult", template.insert("myStatement", "myParameter"));
template.executorControl.verify();
}
@Test
public void testUpdate() throws SQLException {
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.update("myStatement", null);
template.executorControl.setReturnValue(10, 1);
template.executorControl.replay();
given(template.executor.update("myStatement", null)).willReturn(10);
assertEquals(10, template.update("myStatement"));
template.executorControl.verify();
}
@Test
public void testUpdateWithParameter() throws SQLException {
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.update("myStatement", "myParameter");
template.executorControl.setReturnValue(10, 1);
template.executorControl.replay();
given(template.executor.update("myStatement", "myParameter")).willReturn(10);
assertEquals(10, template.update("myStatement", "myParameter"));
template.executorControl.verify();
}
@Test
public void testUpdateWithRequiredRowsAffected() throws SQLException {
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.update("myStatement", "myParameter");
template.executorControl.setReturnValue(10, 1);
template.executorControl.replay();
given(template.executor.update("myStatement", "myParameter")).willReturn(10);
template.update("myStatement", "myParameter", 10);
template.executorControl.verify();
verify(template.executor).update("myStatement", "myParameter");
}
@Test
public void testUpdateWithRequiredRowsAffectedAndInvalidRowCount() throws SQLException {
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.update("myStatement", "myParameter");
template.executorControl.setReturnValue(20, 1);
template.executorControl.replay();
given(template.executor.update("myStatement", "myParameter")).willReturn(20);
try {
template.update("myStatement", "myParameter", 10);
fail("Should have thrown JdbcUpdateAffectedIncorrectNumberOfRowsException");
@@ -345,41 +274,34 @@ public class SqlMapClientTests extends TestCase {
assertEquals(10, ex.getExpectedRowsAffected());
assertEquals(20, ex.getActualRowsAffected());
}
template.executorControl.verify();
}
@Test
public void testDelete() throws SQLException {
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.delete("myStatement", null);
template.executorControl.setReturnValue(10, 1);
template.executorControl.replay();
given(template.executor.delete("myStatement", null)).willReturn(10);
assertEquals(10, template.delete("myStatement"));
template.executorControl.verify();
}
@Test
public void testDeleteWithParameter() throws SQLException {
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.delete("myStatement", "myParameter");
template.executorControl.setReturnValue(10, 1);
template.executorControl.replay();
given(template.executor.delete("myStatement", "myParameter")).willReturn(10);
assertEquals(10, template.delete("myStatement", "myParameter"));
template.executorControl.verify();
}
@Test
public void testDeleteWithRequiredRowsAffected() throws SQLException {
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.delete("myStatement", "myParameter");
template.executorControl.setReturnValue(10, 1);
template.executorControl.replay();
given(template.executor.delete("myStatement", "myParameter")).willReturn(10);
template.delete("myStatement", "myParameter", 10);
template.executorControl.verify();
verify(template.executor).delete("myStatement", "myParameter");
}
@Test
public void testDeleteWithRequiredRowsAffectedAndInvalidRowCount() throws SQLException {
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
template.executor.delete("myStatement", "myParameter");
template.executorControl.setReturnValue(20, 1);
template.executorControl.replay();
given(template.executor.delete("myStatement", "myParameter")).willReturn(20);
try {
template.delete("myStatement", "myParameter", 10);
fail("Should have thrown JdbcUpdateAffectedIncorrectNumberOfRowsException");
@@ -389,20 +311,17 @@ public class SqlMapClientTests extends TestCase {
assertEquals(10, ex.getExpectedRowsAffected());
assertEquals(20, ex.getActualRowsAffected());
}
template.executorControl.verify();
}
@Test
public void testSqlMapClientDaoSupport() throws Exception {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
DataSource ds = mock(DataSource.class);
SqlMapClientDaoSupport testDao = new SqlMapClientDaoSupport() {
};
testDao.setDataSource(ds);
assertEquals(ds, testDao.getDataSource());
MockControl clientControl = MockControl.createControl(SqlMapClient.class);
SqlMapClient client = (SqlMapClient) clientControl.getMock();
clientControl.replay();
SqlMapClient client = mock(SqlMapClient.class);
testDao.setSqlMapClient(client);
assertEquals(client, testDao.getSqlMapClient());
@@ -419,8 +338,7 @@ public class SqlMapClientTests extends TestCase {
private static class TestSqlMapClientTemplate extends SqlMapClientTemplate {
public MockControl executorControl = MockControl.createControl(SqlMapExecutor.class);
public SqlMapExecutor executor = (SqlMapExecutor) executorControl.getMock();
public SqlMapExecutor executor = mock(SqlMapExecutor.class);
@Override
public Object execute(SqlMapClientCallback action) throws DataAccessException {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,21 +16,29 @@
package org.springframework.orm.ibatis.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.easymock.ArgumentsMatcher;
import org.easymock.MockControl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;
@@ -41,42 +49,33 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
/**
* @author Juergen Hoeller
* @author Phillip Webb
* @since 27.02.2005
*/
public class LobTypeHandlerTests extends TestCase {
public class LobTypeHandlerTests {
private MockControl rsControl = MockControl.createControl(ResultSet.class);
private ResultSet rs = (ResultSet) rsControl.getMock();
private MockControl psControl = MockControl.createControl(PreparedStatement.class);
private PreparedStatement ps = (PreparedStatement) psControl.getMock();
private ResultSet rs = mock(ResultSet.class);
private PreparedStatement ps = mock(PreparedStatement.class);
private MockControl lobHandlerControl = MockControl.createControl(LobHandler.class);
private LobHandler lobHandler = (LobHandler) lobHandlerControl.getMock();
private MockControl lobCreatorControl = MockControl.createControl(LobCreator.class);
private LobCreator lobCreator = (LobCreator) lobCreatorControl.getMock();
private LobHandler lobHandler = mock(LobHandler.class);
private LobCreator lobCreator = mock(LobCreator.class);
@Override
protected void setUp() throws SQLException {
rs.findColumn("column");
rsControl.setReturnValue(1);
lobHandler.getLobCreator();
lobHandlerControl.setReturnValue(lobCreator);
lobCreator.close();
lobCreatorControl.setVoidCallable(1);
rsControl.replay();
psControl.replay();
@Before
public void setUp() throws Exception {
given(rs.findColumn("column")).willReturn(1);
given(lobHandler.getLobCreator()).willReturn(lobCreator);
}
public void testClobStringTypeHandler() throws Exception {
lobHandler.getClobAsString(rs, 1);
lobHandlerControl.setReturnValue("content", 2);
lobCreator.setClobAsString(ps, 1, "content");
lobCreatorControl.setVoidCallable(1);
@After
public void tearDown() throws Exception {
verify(lobCreator).close();
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
lobHandlerControl.replay();
lobCreatorControl.replay();
@Test
public void testClobStringTypeHandler() throws Exception {
given(lobHandler.getClobAsString(rs, 1)).willReturn("content");
ClobStringTypeHandler type = new ClobStringTypeHandler(lobHandler);
assertEquals("content", type.valueOf("content"));
@@ -95,19 +94,15 @@ public class LobTypeHandlerTests extends TestCase {
finally {
TransactionSynchronizationManager.clearSynchronization();
}
verify(lobCreator).setClobAsString(ps, 1, "content");
}
@Test
public void testClobStringTypeWithSynchronizedConnection() throws Exception {
DataSource dsTarget = new DriverManagerDataSource();
DataSource ds = new LazyConnectionDataSourceProxy(dsTarget);
lobHandler.getClobAsString(rs, 1);
lobHandlerControl.setReturnValue("content", 2);
lobCreator.setClobAsString(ps, 1, "content");
lobCreatorControl.setVoidCallable(1);
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getClobAsString(rs, 1)).willReturn("content");
ClobStringTypeHandler type = new ClobStringTypeHandler(lobHandler);
assertEquals("content", type.valueOf("content"));
@@ -129,17 +124,13 @@ public class LobTypeHandlerTests extends TestCase {
finally {
TransactionSynchronizationManager.clearSynchronization();
}
verify(lobCreator).setClobAsString(ps, 1, "content");
}
@Test
public void testBlobByteArrayType() throws Exception {
byte[] content = "content".getBytes();
lobHandler.getBlobAsBytes(rs, 1);
lobHandlerControl.setReturnValue(content, 2);
lobCreator.setBlobAsBytes(ps, 1, content);
lobCreatorControl.setVoidCallable(1);
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getBlobAsBytes(rs, 1)).willReturn(content);
BlobByteArrayTypeHandler type = new BlobByteArrayTypeHandler(lobHandler);
assertTrue(Arrays.equals(content, (byte[]) type.valueOf("content")));
@@ -157,33 +148,24 @@ public class LobTypeHandlerTests extends TestCase {
finally {
TransactionSynchronizationManager.clearSynchronization();
}
verify(lobCreator).setBlobAsBytes(ps, 1, content);
}
@Test
public void testBlobSerializableType() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject("content");
oos.close();
lobHandler.getBlobAsBinaryStream(rs, 1);
lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray()), 1);
lobHandler.getBlobAsBinaryStream(rs, 1);
lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray()), 1);
lobCreator.setBlobAsBytes(ps, 1, baos.toByteArray());
lobCreatorControl.setMatcher(new ArgumentsMatcher() {
given(lobHandler.getBlobAsBinaryStream(rs, 1)).willAnswer(new Answer<InputStream>() {
@Override
public boolean matches(Object[] o1, Object[] o2) {
return Arrays.equals((byte[]) o1[2], (byte[]) o2[2]);
}
@Override
public String toString(Object[] objects) {
return null;
public InputStream answer(InvocationOnMock invocation)
throws Throwable {
return new ByteArrayInputStream(baos.toByteArray());
}
});
lobHandlerControl.replay();
lobCreatorControl.replay();
BlobSerializableTypeHandler type = new BlobSerializableTypeHandler(lobHandler);
assertEquals("content", type.valueOf("content"));
assertEquals("content", type.getResult(rs, "column"));
@@ -200,15 +182,12 @@ public class LobTypeHandlerTests extends TestCase {
finally {
TransactionSynchronizationManager.clearSynchronization();
}
verify(lobCreator).setBlobAsBytes(ps, 1, baos.toByteArray());
}
@Test
public void testBlobSerializableTypeWithNull() throws Exception {
lobHandler.getBlobAsBinaryStream(rs, 1);
lobHandlerControl.setReturnValue(null, 2);
lobCreator.setBlobAsBytes(ps, 1, null);
lobHandlerControl.replay();
lobCreatorControl.replay();
given(lobHandler.getBlobAsBinaryStream(rs, 1)).willReturn(null);
BlobSerializableTypeHandler type = new BlobSerializableTypeHandler(lobHandler);
assertEquals(null, type.valueOf(null));
@@ -225,21 +204,6 @@ public class LobTypeHandlerTests extends TestCase {
finally {
TransactionSynchronizationManager.clearSynchronization();
}
verify(lobCreator).setBlobAsBytes(ps, 1, null);
}
@Override
protected void tearDown() {
try {
rsControl.verify();
psControl.verify();
lobHandlerControl.verify();
lobCreatorControl.verify();
}
catch (IllegalStateException ex) {
// ignore: test method didn't call replay
}
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,36 +16,34 @@
package org.springframework.orm.jdo;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import junit.framework.TestCase;
import org.aopalliance.intercept.Interceptor;
import org.aopalliance.intercept.Invocation;
import org.aopalliance.intercept.MethodInvocation;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* @author Juergen Hoeller
* @author Phillip Webb
*/
public class JdoInterceptorTests extends TestCase {
public class JdoInterceptorTests {
@Test
public void testInterceptor() {
MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock();
MockControl pmControl = MockControl.createControl(PersistenceManager.class);
PersistenceManager pm = (PersistenceManager) pmControl.getMock();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm, 1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class);
PersistenceManager pm = mock(PersistenceManager.class);
given(pmf.getPersistenceManager()).willReturn(pm);
JdoInterceptor interceptor = new JdoInterceptor();
interceptor.setPersistenceManagerFactory(pmf);
@@ -56,17 +54,13 @@ public class JdoInterceptorTests extends TestCase {
fail("Should not have thrown Throwable: " + t.getMessage());
}
pmfControl.verify();
pmControl.verify();
verify(pm).close();
}
@Test
public void testInterceptorWithPrebound() {
MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock();
MockControl pmControl = MockControl.createControl(PersistenceManager.class);
PersistenceManager pm = (PersistenceManager) pmControl.getMock();
pmfControl.replay();
pmControl.replay();
PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class);
PersistenceManager pm = mock(PersistenceManager.class);
TransactionSynchronizationManager.bindResource(pmf, new PersistenceManagerHolder(pm));
JdoInterceptor interceptor = new JdoInterceptor();
@@ -80,12 +74,10 @@ public class JdoInterceptorTests extends TestCase {
finally {
TransactionSynchronizationManager.unbindResource(pmf);
}
pmfControl.verify();
pmControl.verify();
}
@SuppressWarnings("unused")
private static class TestInvocation implements MethodInvocation {
private PersistenceManagerFactory persistenceManagerFactory;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,12 +16,20 @@
package org.springframework.orm.jdo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.jdo.JDODataStoreException;
import javax.jdo.JDOException;
import javax.jdo.JDOFatalDataStoreException;
@@ -33,44 +41,29 @@ import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* @author Juergen Hoeller
* @author Phillip Webb
* @since 03.06.2003
*/
public class JdoTemplateTests extends TestCase {
public class JdoTemplateTests {
private MockControl pmfControl;
private PersistenceManagerFactory pmf;
private MockControl pmControl;
private PersistenceManager pm;
@Override
protected void setUp() {
pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
pmf = (PersistenceManagerFactory) pmfControl.getMock();
pmControl = MockControl.createControl(PersistenceManager.class);
pm = (PersistenceManager) pmControl.getMock();
pmf.getConnectionFactory();
pmfControl.setReturnValue(null, 1);
}
@Override
protected void tearDown() {
try {
pmfControl.verify();
pmControl.verify();
}
catch (IllegalStateException ex) {
// ignore: test method didn't call replay
}
@Before
public void setUp() {
pmf = mock(PersistenceManagerFactory.class);
pm = mock(PersistenceManager.class);
}
@Test
public void testTemplateExecuteWithNotAllowCreate() {
JdoTemplate jt = new JdoTemplate();
jt.setPersistenceManagerFactory(pmf);
@@ -89,10 +82,8 @@ public class JdoTemplateTests extends TestCase {
}
}
@Test
public void testTemplateExecuteWithNotAllowCreateAndThreadBound() {
pmfControl.replay();
pmControl.replay();
JdoTemplate jt = new JdoTemplate(pmf);
jt.setAllowCreate(false);
TransactionSynchronizationManager.bindResource(pmf, new PersistenceManagerHolder(pm));
@@ -108,13 +99,9 @@ public class JdoTemplateTests extends TestCase {
TransactionSynchronizationManager.unbindResource(pmf);
}
@Test
public void testTemplateExecuteWithNewPersistenceManager() {
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm, 1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
JdoTemplate jt = new JdoTemplate(pmf);
final List l = new ArrayList();
@@ -126,14 +113,11 @@ public class JdoTemplateTests extends TestCase {
}
});
assertTrue("Correct result list", result == l);
verify(pm).close();
}
@Test
public void testTemplateExecuteWithThreadBoundAndFlushEager() {
pm.flush();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
JdoTemplate jt = new JdoTemplate(pmf);
jt.setFlushEager(true);
jt.setAllowCreate(false);
@@ -148,481 +132,291 @@ public class JdoTemplateTests extends TestCase {
});
assertTrue("Correct result list", result == l);
TransactionSynchronizationManager.unbindResource(pmf);
verify(pm).flush();
}
@Test
public void testGetObjectById() {
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.getObjectById("0", true);
pmControl.setReturnValue("A");
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
given(pm.getObjectById("0", true)).willReturn("A");
JdoTemplate jt = new JdoTemplate(pmf);
assertEquals("A", jt.getObjectById("0"));
verify(pm).close();
}
@Test
public void testGetObjectByIdWithClassAndValue() {
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.getObjectById(String.class, "0");
pmControl.setReturnValue("A");
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
given(pm.getObjectById(String.class, "0")).willReturn("A");
JdoTemplate jt = new JdoTemplate(pmf);
assertEquals("A", jt.getObjectById(String.class, "0"));
verify(pm).close();
}
@Test
public void testEvict() {
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.evict("0");
pmControl.setVoidCallable(1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
JdoTemplate jt = new JdoTemplate(pmf);
jt.evict("0");
verify(pm).evict("0");
verify(pm).close();
}
@Test
public void testEvictAllWithCollection() {
Collection coll = new HashSet();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.evictAll(coll);
pmControl.setVoidCallable(1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
JdoTemplate jt = new JdoTemplate(pmf);
jt.evictAll(coll);
verify(pm).evictAll(coll);
verify(pm).close();
}
@Test
public void testEvictAll() {
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.evictAll();
pmControl.setVoidCallable(1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
JdoTemplate jt = new JdoTemplate(pmf);
jt.evictAll();
verify(pm).evictAll();
verify(pm).close();
}
@Test
public void testRefresh() {
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.refresh("0");
pmControl.setVoidCallable(1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
JdoTemplate jt = new JdoTemplate(pmf);
jt.refresh("0");
verify(pm).refresh("0");
verify(pm).close();
}
@Test
public void testRefreshAllWithCollection() {
Collection coll = new HashSet();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.refreshAll(coll);
pmControl.setVoidCallable(1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
JdoTemplate jt = new JdoTemplate(pmf);
jt.refreshAll(coll);
verify(pm).refreshAll(coll);
verify(pm).close();
}
@Test
public void testRefreshAll() {
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.refreshAll();
pmControl.setVoidCallable(1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
JdoTemplate jt = new JdoTemplate(pmf);
jt.refreshAll();
verify(pm).refreshAll();
verify(pm).close();
}
@Test
public void testMakePersistent() {
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.makePersistent("0");
pmControl.setReturnValue(null, 1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
JdoTemplate jt = new JdoTemplate(pmf);
jt.makePersistent("0");
verify(pm).makePersistent("0");
verify(pm).close();
}
@Test
public void testMakePersistentAll() {
Collection coll = new HashSet();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.makePersistentAll(coll);
pmControl.setReturnValue(null, 1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
JdoTemplate jt = new JdoTemplate(pmf);
jt.makePersistentAll(coll);
verify(pm).makePersistentAll(coll);
verify(pm).close();
}
@Test
public void testDeletePersistent() {
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.deletePersistent("0");
pmControl.setVoidCallable(1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
JdoTemplate jt = new JdoTemplate(pmf);
jt.deletePersistent("0");
verify(pm).deletePersistent("0");
verify(pm).close();
}
@Test
public void testDeletePersistentAll() {
Collection coll = new HashSet();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.deletePersistentAll(coll);
pmControl.setVoidCallable(1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
JdoTemplate jt = new JdoTemplate(pmf);
jt.deletePersistentAll(coll);
verify(pm).deletePersistentAll(coll);
verify(pm).close();
}
@Test
public void testDetachCopy() {
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.detachCopy("0");
pmControl.setReturnValue("0x", 1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
given(pm.detachCopy("0")).willReturn("0x");
JdoTemplate jt = new JdoTemplate(pmf);
assertEquals("0x", jt.detachCopy("0"));
verify(pm).close();
}
@Test
public void testDetachCopyAll() {
Collection attached = new HashSet();
Collection detached = new HashSet();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.detachCopyAll(attached);
pmControl.setReturnValue(detached, 1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
given(pm.detachCopyAll(attached)).willReturn(detached);
JdoTemplate jt = new JdoTemplate(pmf);
assertEquals(detached, jt.detachCopyAll(attached));
verify(pm).close();
}
@Test
public void testFlush() {
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.flush();
pmControl.setVoidCallable(1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
JdoTemplate jt = new JdoTemplate(pmf);
jt.flush();
verify(pm).flush();
verify(pm).close();
}
@Test
public void testFlushWithDialect() {
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.flush();
pmControl.setVoidCallable(1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
JdoTemplate jt = new JdoTemplate(pmf);
jt.flush();
verify(pm).flush();
verify(pm).close();
}
@Test
public void testFind() {
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.newQuery(String.class);
pmControl.setReturnValue(query);
Query query = mock(Query.class);
given(pmf.getPersistenceManager()).willReturn(pm);
given(pm.newQuery(String.class)).willReturn(query);
Collection coll = new HashSet();
query.execute();
queryControl.setReturnValue(coll);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
queryControl.replay();
given(query.execute()).willReturn(coll);
JdoTemplate jt = new JdoTemplate(pmf);
assertEquals(coll, jt.find(String.class));
queryControl.verify();
verify(pm).close();
}
@Test
public void testFindWithFilter() {
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.newQuery(String.class, "a == b");
pmControl.setReturnValue(query);
Query query = mock(Query.class);
given(pmf.getPersistenceManager()).willReturn(pm);
given(pm.newQuery(String.class, "a == b")).willReturn(query);
Collection coll = new HashSet();
query.execute();
queryControl.setReturnValue(coll);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
queryControl.replay();
given(query.execute()).willReturn(coll);
JdoTemplate jt = new JdoTemplate(pmf);
assertEquals(coll, jt.find(String.class, "a == b"));
queryControl.verify();
verify(pm).close();
}
@Test
public void testFindWithFilterAndOrdering() {
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.newQuery(String.class, "a == b");
pmControl.setReturnValue(query);
query.setOrdering("c asc");
queryControl.setVoidCallable(1);
Query query = mock(Query.class);
given(pmf.getPersistenceManager()).willReturn(pm);
given(pm.newQuery(String.class, "a == b")).willReturn(query);
Collection coll = new HashSet();
query.execute();
queryControl.setReturnValue(coll);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
queryControl.replay();
given(query.execute()).willReturn(coll);
JdoTemplate jt = new JdoTemplate(pmf);
assertEquals(coll, jt.find(String.class, "a == b", "c asc"));
queryControl.verify();
verify(query).setOrdering("c asc");
verify(pm).close();
}
@Test
public void testFindWithParameterArray() {
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.newQuery(String.class, "a == b");
pmControl.setReturnValue(query);
query.declareParameters("params");
queryControl.setVoidCallable(1);
Query query = mock(Query.class);
given(pmf.getPersistenceManager()).willReturn(pm);
given(pm.newQuery(String.class, "a == b")).willReturn(query);
Object[] values = new Object[0];
Collection coll = new HashSet();
query.executeWithArray(values);
queryControl.setReturnValue(coll);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
queryControl.replay();
given(query.executeWithArray(values)).willReturn(coll);
JdoTemplate jt = new JdoTemplate(pmf);
assertEquals(coll, jt.find(String.class, "a == b", "params", values));
queryControl.verify();
verify(query).declareParameters("params");
verify(pm).close();
}
@Test
public void testFindWithParameterArrayAndOrdering() {
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.newQuery(String.class, "a == b");
pmControl.setReturnValue(query);
query.declareParameters("params");
queryControl.setVoidCallable(1);
query.setOrdering("c asc");
queryControl.setVoidCallable(1);
Query query = mock(Query.class);
given(pmf.getPersistenceManager()).willReturn(pm);
given(pm.newQuery(String.class, "a == b")).willReturn(query);
Object[] values = new Object[0];
Collection coll = new HashSet();
query.executeWithArray(values);
queryControl.setReturnValue(coll);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
queryControl.replay();
given(query.executeWithArray(values)).willReturn(coll);
JdoTemplate jt = new JdoTemplate(pmf);
assertEquals(coll, jt.find(String.class, "a == b", "params", values, "c asc"));
queryControl.verify();
verify(query).declareParameters("params");
verify(query).setOrdering("c asc");
verify(pm).close();
}
@Test
public void testFindWithParameterMap() {
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.newQuery(String.class, "a == b");
pmControl.setReturnValue(query);
query.declareParameters("params");
queryControl.setVoidCallable(1);
Query query = mock(Query.class);
given(pmf.getPersistenceManager()).willReturn(pm);
given(pm.newQuery(String.class, "a == b")).willReturn(query);
Map values = new HashMap();
Collection coll = new HashSet();
query.executeWithMap(values);
queryControl.setReturnValue(coll);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
queryControl.replay();
given(query.executeWithMap(values)).willReturn(coll);
JdoTemplate jt = new JdoTemplate(pmf);
assertEquals(coll, jt.find(String.class, "a == b", "params", values));
queryControl.verify();
verify(query).declareParameters("params");
verify(pm).close();
}
@Test
public void testFindWithParameterMapAndOrdering() {
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.newQuery(String.class, "a == b");
pmControl.setReturnValue(query);
query.declareParameters("params");
queryControl.setVoidCallable(1);
query.setOrdering("c asc");
queryControl.setVoidCallable(1);
Query query = mock(Query.class);
given(pmf.getPersistenceManager()).willReturn(pm);
given(pm.newQuery(String.class, "a == b")).willReturn(query);
Map values = new HashMap();
Collection coll = new HashSet();
query.executeWithMap(values);
queryControl.setReturnValue(coll);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
queryControl.replay();
given(query.executeWithMap(values)).willReturn(coll);
JdoTemplate jt = new JdoTemplate(pmf);
assertEquals(coll, jt.find(String.class, "a == b", "params", values, "c asc"));
queryControl.verify();
verify(query).declareParameters("params");
verify(query).setOrdering("c asc");
verify(pm).close();
}
@Test
public void testFindWithLanguageAndQueryObject() {
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.newQuery(Query.SQL, "some SQL");
pmControl.setReturnValue(query);
Query query = mock(Query.class);
given(pmf.getPersistenceManager()).willReturn(pm);
given(pm.newQuery(Query.SQL, "some SQL")).willReturn(query);
Collection coll = new HashSet();
query.execute();
queryControl.setReturnValue(coll);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
queryControl.replay();
given(query.execute()).willReturn(coll);
JdoTemplate jt = new JdoTemplate(pmf);
assertEquals(coll, jt.find(Query.SQL, "some SQL"));
queryControl.verify();
verify(pm).close();
}
@Test
public void testFindWithQueryString() {
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.newQuery("single string query");
pmControl.setReturnValue(query);
Query query = mock(Query.class);
given(pmf.getPersistenceManager()).willReturn(pm);
given(pm.newQuery("single string query")).willReturn(query);
Collection coll = new HashSet();
query.execute();
queryControl.setReturnValue(coll);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
queryControl.replay();
given(query.execute()).willReturn(coll);
JdoTemplate jt = new JdoTemplate(pmf);
assertEquals(coll, jt.find("single string query"));
queryControl.verify();
verify(pm).close();
}
@Test
public void testFindByNamedQuery() {
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm);
pm.newNamedQuery(String.class, "some query name");
pmControl.setReturnValue(query);
Query query = mock(Query.class);
given(pmf.getPersistenceManager()).willReturn(pm);
given(pm.newNamedQuery(String.class, "some query name")).willReturn(query);
Collection coll = new HashSet();
query.execute();
queryControl.setReturnValue(coll);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
queryControl.replay();
given(query.execute()).willReturn(coll);
JdoTemplate jt = new JdoTemplate(pmf);
assertEquals(coll, jt.findByNamedQuery(String.class, "some query name"));
queryControl.verify();
verify(pm).close();
}
@Test
public void testTemplateExceptions() {
try {
createTemplate().execute(new JdoCallback() {
@@ -716,13 +510,11 @@ public class JdoTemplateTests extends TestCase {
}
}
@Test
public void testTranslateException() {
MockControl dialectControl = MockControl.createControl(JdoDialect.class);
JdoDialect dialect = (JdoDialect) dialectControl.getMock();
JdoDialect dialect = mock(JdoDialect.class);
final JDOException ex = new JDOException();
dialect.translateException(ex);
dialectControl.setReturnValue(new DataIntegrityViolationException("test", ex));
dialectControl.replay();
given(dialect.translateException(ex)).willReturn(new DataIntegrityViolationException("test", ex));
try {
JdoTemplate template = createTemplate();
template.setJdoDialect(dialect);
@@ -737,20 +529,10 @@ public class JdoTemplateTests extends TestCase {
catch (DataIntegrityViolationException dive) {
// expected
}
dialectControl.verify();
}
private JdoTemplate createTemplate() {
pmfControl.reset();
pmControl.reset();
pmf.getConnectionFactory();
pmfControl.setReturnValue(null, 1);
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm, 1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
return new JdoTemplate(pmf);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,11 @@
package org.springframework.orm.jdo;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
@@ -23,19 +28,18 @@ import java.util.Properties;
import javax.jdo.JDOFatalUserException;
import javax.jdo.PersistenceManagerFactory;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
/**
* @author Juergen Hoeller
* @author Phillip Webb
*/
public class LocalPersistenceManagerFactoryTests extends TestCase {
public class LocalPersistenceManagerFactoryTests {
@Test
public void testLocalPersistenceManagerFactoryBean() throws IOException {
MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
final PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock();
final PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class);
LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() {
@Override
protected PersistenceManagerFactory newPersistenceManagerFactory(Map props) {
@@ -47,6 +51,7 @@ public class LocalPersistenceManagerFactoryTests extends TestCase {
assertSame(pmf, pmfb.getObject());
}
@Test
public void testLocalPersistenceManagerFactoryBeanWithInvalidSettings() throws IOException {
LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean();
try {
@@ -58,6 +63,7 @@ public class LocalPersistenceManagerFactoryTests extends TestCase {
}
}
@Test
public void testLocalPersistenceManagerFactoryBeanWithIncompleteProperties() throws IOException {
LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean();
Properties props = new Properties();
@@ -72,6 +78,7 @@ public class LocalPersistenceManagerFactoryTests extends TestCase {
}
}
@Test
public void testLocalPersistenceManagerFactoryBeanWithInvalidProperty() throws IOException {
LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() {
@Override
@@ -92,6 +99,7 @@ public class LocalPersistenceManagerFactoryTests extends TestCase {
}
}
@Test
public void testLocalPersistenceManagerFactoryBeanWithFile() throws IOException {
LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() {
@Override
@@ -110,6 +118,7 @@ public class LocalPersistenceManagerFactoryTests extends TestCase {
}
}
@Test
public void testLocalPersistenceManagerFactoryBeanWithName() throws IOException {
LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() {
@Override
@@ -128,6 +137,7 @@ public class LocalPersistenceManagerFactoryTests extends TestCase {
}
}
@Test
public void testLocalPersistenceManagerFactoryBeanWithNameAndProperties() throws IOException {
LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() {
@Override

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,28 +16,28 @@
package org.springframework.orm.jdo.support;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.List;
import javax.jdo.PersistenceManagerFactory;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.orm.jdo.JdoTemplate;
/**
* @author Juergen Hoeller
* @author Phillip Webb
* @since 30.07.2003
*/
public class JdoDaoSupportTests extends TestCase {
public class JdoDaoSupportTests {
@Test
public void testJdoDaoSupportWithPersistenceManagerFactory() throws Exception {
MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock();
PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class);
pmf.getConnectionFactory();
pmfControl.setReturnValue(null, 1);
pmfControl.replay();
final List test = new ArrayList();
JdoDaoSupport dao = new JdoDaoSupport() {
@Override
@@ -50,9 +50,9 @@ public class JdoDaoSupportTests extends TestCase {
assertEquals("Correct PersistenceManagerFactory", pmf, dao.getPersistenceManagerFactory());
assertEquals("Correct JdoTemplate", pmf, dao.getJdoTemplate().getPersistenceManagerFactory());
assertEquals("initDao called", test.size(), 1);
pmfControl.verify();
}
@Test
public void testJdoDaoSupportWithJdoTemplate() throws Exception {
JdoTemplate template = new JdoTemplate();
final List test = new ArrayList();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,15 @@
package org.springframework.orm.jdo.support;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.io.IOException;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.FilterChain;
@@ -24,9 +32,7 @@ import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.mock.web.test.MockFilterConfig;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
@@ -40,15 +46,15 @@ import org.springframework.web.context.support.StaticWebApplicationContext;
/**
* @author Juergen Hoeller
* @author Chris Beams
* @author Phillip Webb
* @since 15.06.2004
*/
public class OpenPersistenceManagerInViewTests extends TestCase {
public class OpenPersistenceManagerInViewTests {
@Test
public void testOpenPersistenceManagerInViewInterceptor() throws Exception {
MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock();
MockControl pmControl = MockControl.createControl(PersistenceManager.class);
PersistenceManager pm = (PersistenceManager) pmControl.getMock();
PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class);
PersistenceManager pm = mock(PersistenceManager.class);
OpenPersistenceManagerInViewInterceptor interceptor = new OpenPersistenceManagerInViewInterceptor();
interceptor.setPersistenceManagerFactory(pmf);
@@ -56,10 +62,7 @@ public class OpenPersistenceManagerInViewTests extends TestCase {
MockServletContext sc = new MockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(sc);
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm, 1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
interceptor.preHandle(new ServletWebRequest(request));
assertTrue(TransactionSynchronizationManager.hasResource(pmf));
@@ -77,54 +80,23 @@ public class OpenPersistenceManagerInViewTests extends TestCase {
interceptor.postHandle(new ServletWebRequest(request), null);
interceptor.afterCompletion(new ServletWebRequest(request), null);
pmfControl.verify();
pmControl.verify();
pmfControl.reset();
pmControl.reset();
pmfControl.replay();
pmControl.replay();
interceptor.postHandle(new ServletWebRequest(request), null);
assertTrue(TransactionSynchronizationManager.hasResource(pmf));
pmfControl.verify();
pmControl.verify();
pmfControl.reset();
pmControl.reset();
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
interceptor.afterCompletion(new ServletWebRequest(request), null);
assertFalse(TransactionSynchronizationManager.hasResource(pmf));
pmfControl.verify();
pmControl.verify();
}
@Test
public void testOpenPersistenceManagerInViewFilter() throws Exception {
MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
final PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock();
MockControl pmControl = MockControl.createControl(PersistenceManager.class);
PersistenceManager pm = (PersistenceManager) pmControl.getMock();
final PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class);
PersistenceManager pm = mock(PersistenceManager.class);
pmf.getPersistenceManager();
pmfControl.setReturnValue(pm, 1);
pm.close();
pmControl.setVoidCallable(1);
pmfControl.replay();
pmControl.replay();
given(pmf.getPersistenceManager()).willReturn(pm);
final PersistenceManagerFactory pmf2 = mock(PersistenceManagerFactory.class);
PersistenceManager pm2 = mock(PersistenceManager.class);
MockControl pmf2Control = MockControl.createControl(PersistenceManagerFactory.class);
final PersistenceManagerFactory pmf2 = (PersistenceManagerFactory) pmf2Control.getMock();
MockControl pm2Control = MockControl.createControl(PersistenceManager.class);
PersistenceManager pm2 = (PersistenceManager) pm2Control.getMock();
pmf2.getPersistenceManager();
pmf2Control.setReturnValue(pm2, 1);
pm2.close();
pm2Control.setVoidCallable(1);
pmf2Control.replay();
pm2Control.replay();
given(pmf2.getPersistenceManager()).willReturn(pm2);
MockServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
@@ -171,10 +143,8 @@ public class OpenPersistenceManagerInViewTests extends TestCase {
assertFalse(TransactionSynchronizationManager.hasResource(pmf2));
assertNotNull(request.getAttribute("invoked"));
pmfControl.verify();
pmControl.verify();
pmf2Control.verify();
pm2Control.verify();
verify(pm).close();
verify(pm2).close();
wac.close();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,13 +16,17 @@
package org.springframework.orm.jpa;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.spi.PersistenceUnitInfo;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.After;
import org.junit.Before;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
@@ -31,18 +35,23 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Phillip Webb
*/
public abstract class AbstractEntityManagerFactoryBeanTests extends TestCase {
protected static MockControl emfMc;
public abstract class AbstractEntityManagerFactoryBeanTests {
protected static EntityManagerFactory mockEmf;
@Before
public void setUp() throws Exception {
mockEmf = mock(EntityManagerFactory.class);
}
@Override
protected void setUp() throws Exception {
emfMc = MockControl.createControl(EntityManagerFactory.class);
mockEmf = (EntityManagerFactory) emfMc.getMock();
@After
public void tearDown() throws Exception {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
}
protected void checkInvariants(AbstractEntityManagerFactoryBean demf) {
@@ -56,14 +65,6 @@ public abstract class AbstractEntityManagerFactoryBeanTests extends TestCase {
assertSame(emfi.getNativeEntityManagerFactory(), mockEmf);
}
@Override
protected void tearDown() throws Exception {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
}
protected static class DummyEntityManagerFactoryBean extends AbstractEntityManagerFactoryBean {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -48,6 +48,7 @@ public class ApplicationManagedEntityManagerIntegrationTests extends AbstractEnt
assertTrue(Proxy.isProxyClass(em.getClass()));
Query q = em.createQuery("select p from Person as p");
List<Person> people = q.getResultList();
assertNotNull(people);
assertTrue("Should be open to start with", em.isOpen());
em.close();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,35 +16,29 @@
package org.springframework.orm.jpa;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.OptimisticLockException;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.support.DefaultTransactionDefinition;
/**
*
* @author Costin Leau
*
* @author Phillip Webb
*/
public class DefaultJpaDialectTests extends TestCase {
JpaDialect dialect;
public class DefaultJpaDialectTests {
@Override
protected void setUp() throws Exception {
dialect = new DefaultJpaDialect();
}
@Override
protected void tearDown() throws Exception {
dialect = null;
}
private JpaDialect dialect = new DefaultJpaDialect();
@Test
public void testDefaultTransactionDefinition() throws Exception {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
@@ -58,26 +52,18 @@ public class DefaultJpaDialectTests extends TestCase {
}
}
@Test
public void testDefaultBeginTransaction() throws Exception {
TransactionDefinition definition = new DefaultTransactionDefinition();
MockControl entityControl = MockControl.createControl(EntityManager.class);
EntityManager entityManager = (EntityManager) entityControl.getMock();
EntityManager entityManager = mock(EntityManager.class);
EntityTransaction entityTx = mock(EntityTransaction.class);
MockControl txControl = MockControl.createControl(EntityTransaction.class);
EntityTransaction entityTx = (EntityTransaction) txControl.getMock();
entityControl.expectAndReturn(entityManager.getTransaction(), entityTx);
entityTx.begin();
entityControl.replay();
txControl.replay();
given(entityManager.getTransaction()).willReturn(entityTx);
dialect.beginTransaction(entityManager, definition);
entityControl.verify();
txControl.verify();
}
@Test
public void testTranslateException() {
OptimisticLockException ex = new OptimisticLockException();
assertEquals(

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,19 +16,17 @@
package org.springframework.orm.jpa;
import static org.mockito.Mockito.verify;
import org.junit.Test;
/**
* @author Rod Johnson
* @author Phillip Webb
*/
public class EntityManagerFactoryBeanSupportTests extends AbstractEntityManagerFactoryBeanTests {
@Override
protected void setUp() throws Exception {
super.setUp();
mockEmf.close();
emfMc.setVoidCallable();
emfMc.replay();
}
@Test
public void testHookIsCalled() throws Exception {
DummyEntityManagerFactoryBean demf = new DummyEntityManagerFactoryBean(mockEmf);
@@ -39,7 +37,7 @@ public class EntityManagerFactoryBeanSupportTests extends AbstractEntityManagerF
// Should trigger close method expected by EntityManagerFactory mock
demf.destroy();
emfMc.verify();
verify(mockEmf).close();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,13 @@
package org.springframework.orm.jpa;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
@@ -26,9 +33,7 @@ import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException;
import javax.persistence.TransactionRequiredException;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.EmptyResultDataAccessException;
@@ -40,13 +45,15 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
* @author Costin Leau
* @author Rod Johnson
* @author Juergen Hoeller
* @author Phillip Webb
*/
public class EntityManagerFactoryUtilsTests extends TestCase {
public class EntityManagerFactoryUtilsTests {
/*
* Test method for
* 'org.springframework.orm.jpa.EntityManagerFactoryUtils.doGetEntityManager(EntityManagerFactory)'
*/
@Test
public void testDoGetEntityManager() {
// test null assertion
try {
@@ -56,34 +63,25 @@ public class EntityManagerFactoryUtilsTests extends TestCase {
catch (IllegalArgumentException ex) {
// it's okay
}
MockControl mockControl = MockControl.createControl(EntityManagerFactory.class);
EntityManagerFactory factory = (EntityManagerFactory) mockControl.getMock();
EntityManagerFactory factory = mock(EntityManagerFactory.class);
mockControl.replay();
// no tx active
assertNull(EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null));
mockControl.verify();
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
}
@Test
public void testDoGetEntityManagerWithTx() throws Exception {
try {
MockControl mockControl = MockControl.createControl(EntityManagerFactory.class);
EntityManagerFactory factory = (EntityManagerFactory) mockControl.getMock();
MockControl managerControl = MockControl.createControl(EntityManager.class);
EntityManager manager = (EntityManager) managerControl.getMock();
EntityManagerFactory factory = mock(EntityManagerFactory.class);
EntityManager manager = mock(EntityManager.class);
TransactionSynchronizationManager.initSynchronization();
mockControl.expectAndReturn(factory.createEntityManager(), manager);
given(factory.createEntityManager()).willReturn(manager);
mockControl.replay();
// no tx active
assertSame(manager, EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null));
assertSame(manager, ((EntityManagerHolder)TransactionSynchronizationManager.unbindResource(factory)).getEntityManager());
mockControl.verify();
}
finally {
TransactionSynchronizationManager.clearSynchronization();
@@ -92,6 +90,7 @@ public class EntityManagerFactoryUtilsTests extends TestCase {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
}
@Test
public void testTranslatesIllegalStateException() {
IllegalStateException ise = new IllegalStateException();
DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ise);
@@ -99,6 +98,7 @@ public class EntityManagerFactoryUtilsTests extends TestCase {
assertTrue(dex instanceof InvalidDataAccessApiUsageException);
}
@Test
public void testTranslatesIllegalArgumentException() {
IllegalArgumentException iae = new IllegalArgumentException();
DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(iae);
@@ -109,6 +109,7 @@ public class EntityManagerFactoryUtilsTests extends TestCase {
/**
* We do not convert unknown exceptions. They may result from user code.
*/
@Test
public void testDoesNotTranslateUnfamiliarException() {
UnsupportedOperationException userRuntimeException = new UnsupportedOperationException();
assertNull(
@@ -120,6 +121,7 @@ public class EntityManagerFactoryUtilsTests extends TestCase {
* Test method for
* 'org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessException(PersistenceException)'
*/
@Test
@SuppressWarnings("serial")
public void testConvertJpaPersistenceException() {
EntityNotFoundException entityNotFound = new EntityNotFoundException();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,59 +16,57 @@
package org.springframework.orm.jpa;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import junit.framework.TestCase;
import org.aopalliance.intercept.Interceptor;
import org.aopalliance.intercept.Invocation;
import org.aopalliance.intercept.MethodInvocation;
import org.easymock.MockControl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* @author Costin Leau
* @author Phillip Webb
*/
public class JpaInterceptorTests extends TestCase {
private MockControl factoryControl, managerControl;
public class JpaInterceptorTests {
private EntityManagerFactory factory;
private EntityManager entityManager;
@Override
protected void setUp() throws Exception {
factoryControl = MockControl.createControl(EntityManagerFactory.class);
factory = (EntityManagerFactory) factoryControl.getMock();
managerControl = MockControl.createControl(EntityManager.class);
entityManager = (EntityManager) managerControl.getMock();
@Before
public void setUp() throws Exception {
factory = mock(EntityManagerFactory.class);
entityManager = mock(EntityManager.class);
}
@Override
protected void tearDown() throws Exception {
@After
public void tearDown() throws Exception {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
factoryControl = null;
factory = null;
managerControl = null;
entityManager = null;
}
@Test
public void testInterceptorWithNewEntityManager() throws PersistenceException {
factoryControl.expectAndReturn(factory.createEntityManager(), entityManager);
managerControl.expectAndReturn(entityManager.isOpen(), true);
entityManager.close();
factoryControl.replay();
managerControl.replay();
given(factory.createEntityManager()).willReturn(entityManager);
given(entityManager.isOpen()).willReturn(true);
JpaInterceptor interceptor = new JpaInterceptor();
interceptor.setEntityManagerFactory(factory);
@@ -79,17 +77,13 @@ public class JpaInterceptorTests extends TestCase {
fail("Should not have thrown Throwable: " + t.getMessage());
}
factoryControl.verify();
managerControl.verify();
verify(entityManager).close();
}
@Test
public void testInterceptorWithNewEntityManagerAndLazyFlush() throws PersistenceException {
factoryControl.expectAndReturn(factory.createEntityManager(), entityManager);
managerControl.expectAndReturn(entityManager.isOpen(), true);
entityManager.close();
factoryControl.replay();
managerControl.replay();
given(factory.createEntityManager()).willReturn(entityManager);
given(entityManager.isOpen()).willReturn(true);
JpaInterceptor interceptor = new JpaInterceptor();
interceptor.setFlushEager(false);
@@ -101,14 +95,11 @@ public class JpaInterceptorTests extends TestCase {
fail("Should not have thrown Throwable: " + t.getMessage());
}
factoryControl.verify();
managerControl.verify();
verify(entityManager).close();
}
@Test
public void testInterceptorWithThreadBound() {
factoryControl.replay();
managerControl.replay();
TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(entityManager));
JpaInterceptor interceptor = new JpaInterceptor();
interceptor.setEntityManagerFactory(factory);
@@ -121,18 +112,10 @@ public class JpaInterceptorTests extends TestCase {
finally {
TransactionSynchronizationManager.unbindResource(factory);
}
factoryControl.verify();
managerControl.verify();
}
@Test
public void testInterceptorWithThreadBoundAndFlushEager() throws PersistenceException {
//entityManager.setFlushMode(FlushModeType.AUTO);
entityManager.flush();
factoryControl.replay();
managerControl.replay();
TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(entityManager));
JpaInterceptor interceptor = new JpaInterceptor();
interceptor.setFlushEager(true);
@@ -147,17 +130,11 @@ public class JpaInterceptorTests extends TestCase {
TransactionSynchronizationManager.unbindResource(factory);
}
factoryControl.verify();
managerControl.verify();
verify(entityManager).flush();
}
@Test
public void testInterceptorWithThreadBoundAndFlushCommit() {
//entityManager.setFlushMode(FlushModeType.COMMIT);
//entityManager.flush();
factoryControl.replay();
managerControl.replay();
TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(entityManager));
JpaInterceptor interceptor = new JpaInterceptor();
interceptor.setFlushEager(false);
@@ -171,22 +148,15 @@ public class JpaInterceptorTests extends TestCase {
finally {
TransactionSynchronizationManager.unbindResource(factory);
}
factoryControl.verify();
managerControl.verify();
}
@Test
public void testInterceptorWithFlushFailure() throws Throwable {
factoryControl.expectAndReturn(factory.createEntityManager(), entityManager);
entityManager.flush();
given(factory.createEntityManager()).willReturn(entityManager);
PersistenceException exception = new PersistenceException();
managerControl.setThrowable(exception, 1);
managerControl.expectAndReturn(entityManager.isOpen(), true);
entityManager.close();
factoryControl.replay();
managerControl.replay();
willThrow(exception).given(entityManager).flush();
given(entityManager.isOpen()).willReturn(true);
JpaInterceptor interceptor = new JpaInterceptor();
interceptor.setFlushEager(true);
@@ -200,21 +170,16 @@ public class JpaInterceptorTests extends TestCase {
assertEquals(exception, ex.getCause());
}
factoryControl.verify();
managerControl.verify();
verify(entityManager).close();
}
@Test
public void testInterceptorWithFlushFailureWithoutConversion() throws Throwable {
factoryControl.expectAndReturn(factory.createEntityManager(), entityManager);
entityManager.flush();
given(factory.createEntityManager()).willReturn(entityManager);
PersistenceException exception = new PersistenceException();
managerControl.setThrowable(exception, 1);
managerControl.expectAndReturn(entityManager.isOpen(), true);
entityManager.close();
factoryControl.replay();
managerControl.replay();
willThrow(exception).given(entityManager).flush();
given(entityManager.isOpen()).willReturn(true);
JpaInterceptor interceptor = new JpaInterceptor();
interceptor.setFlushEager(true);
@@ -229,11 +194,11 @@ public class JpaInterceptorTests extends TestCase {
assertEquals(exception, ex);
}
factoryControl.verify();
managerControl.verify();
verify(entityManager).close();
}
@SuppressWarnings("unused")
private static class TestInvocation implements MethodInvocation {
private EntityManagerFactory entityManagerFactory;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,61 +16,58 @@
package org.springframework.orm.jpa;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Before;
import org.junit.Test;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* @author Costin Leau
* @author Phillip Webb
*/
public class JpaTemplateTests extends TestCase {
public class JpaTemplateTests {
private JpaTemplate template;
private MockControl factoryControl, managerControl;
private EntityManager manager;
private EntityManagerFactory factory;
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
template = new JpaTemplate();
factoryControl = MockControl.createControl(EntityManagerFactory.class);
factory = (EntityManagerFactory) factoryControl.getMock();
managerControl = MockControl.createControl(EntityManager.class);
manager = (EntityManager) managerControl.getMock();
factory = mock(EntityManagerFactory.class);
manager = mock(EntityManager.class);
template.setEntityManager(manager);
template.afterPropertiesSet();
}
@Override
protected void tearDown() throws Exception {
template = null;
factoryControl = null;
managerControl = null;
manager = null;
factory = null;
}
/*
* Test method for
* 'org.springframework.orm.jpa.JpaTemplate.JpaTemplate(EntityManagerFactory)'
*/
@Test
public void testJpaTemplateEntityManagerFactory() {
}
@@ -79,6 +76,7 @@ public class JpaTemplateTests extends TestCase {
* Test method for
* 'org.springframework.orm.jpa.JpaTemplate.JpaTemplate(EntityManager)'
*/
@Test
public void testJpaTemplateEntityManager() {
}
@@ -87,14 +85,12 @@ public class JpaTemplateTests extends TestCase {
* Test method for
* 'org.springframework.orm.jpa.JpaTemplate.execute(JpaCallback)'
*/
@Test
public void testExecuteJpaCallback() {
template.setExposeNativeEntityManager(true);
template.setEntityManager(manager);
template.afterPropertiesSet();
managerControl.replay();
factoryControl.replay();
template.execute(new JpaCallback() {
@Override
@@ -113,22 +109,18 @@ public class JpaTemplateTests extends TestCase {
return null;
}
});
managerControl.verify();
factoryControl.verify();
}
/*
* Test method for
* 'org.springframework.orm.jpa.JpaTemplate.executeFind(JpaCallback)'
*/
@Test
public void testExecuteFind() {
template.setEntityManager(manager);
template.setExposeNativeEntityManager(true);
template.afterPropertiesSet();
managerControl.replay();
factoryControl.replay();
try {
template.executeFind(new JpaCallback() {
@@ -143,28 +135,23 @@ public class JpaTemplateTests extends TestCase {
catch (DataAccessException e) {
// expected
}
managerControl.verify();
factoryControl.verify();
}
/*
* Test method for
* 'org.springframework.orm.jpa.JpaTemplate.execute(JpaCallback, boolean)'
*/
@Test
public void testExecuteJpaCallbackBoolean() {
template = new JpaTemplate();
template.setExposeNativeEntityManager(false);
template.setEntityManagerFactory(factory);
template.afterPropertiesSet();
factoryControl.expectAndReturn(factory.createEntityManager(), manager);
managerControl.expectAndReturn(manager.isOpen(), true);
given(factory.createEntityManager()).willReturn(manager);
given(manager.isOpen()).willReturn(true);
manager.close();
managerControl.replay();
factoryControl.replay();
template.execute(new JpaCallback() {
@Override
public Object doInJpa(EntityManager em) throws PersistenceException {
@@ -172,19 +159,15 @@ public class JpaTemplateTests extends TestCase {
return null;
}
}, true);
managerControl.verify();
factoryControl.verify();
}
@Test
public void testExecuteJpaCallbackBooleanWithPrebound() {
template.setExposeNativeEntityManager(false);
template.setEntityManagerFactory(factory);
template.afterPropertiesSet();
TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));
managerControl.replay();
factoryControl.replay();
try {
template.execute(new JpaCallback() {
@@ -195,9 +178,6 @@ public class JpaTemplateTests extends TestCase {
return null;
}
}, true);
managerControl.verify();
factoryControl.verify();
}
finally {
TransactionSynchronizationManager.unbindResource(factory);
@@ -208,9 +188,8 @@ public class JpaTemplateTests extends TestCase {
* Test method for
* 'org.springframework.orm.jpa.JpaTemplate.createSharedEntityManager(EntityManager)'
*/
@Test
public void testCreateEntityManagerProxy() {
manager.clear();
managerControl.replay();
EntityManager proxy = template.createEntityManagerProxy(manager);
assertNotSame(manager, proxy);
@@ -220,24 +199,20 @@ public class JpaTemplateTests extends TestCase {
proxy.close();
proxy.clear();
managerControl.verify();
verify(manager).clear();
}
/*
* Test method for 'org.springframework.orm.jpa.JpaTemplate.find(Class<T>,
* Object) <T>'
*/
@Test
public void testFindClassOfTObject() {
Integer result = new Integer(1);
Object id = new Object();
managerControl.expectAndReturn(manager.find(Number.class, id), result);
managerControl.replay();
factoryControl.replay();
given(manager.find(Number.class, id)).willReturn(result);
assertSame(result, template.find(Number.class, id));
managerControl.verify();
factoryControl.verify();
}
/*
@@ -245,172 +220,122 @@ public class JpaTemplateTests extends TestCase {
* 'org.springframework.orm.jpa.JpaTemplate.getReference(Class<T>, Object)
* <T>'
*/
@Test
public void testGetReference() {
Integer reference = new Integer(1);
Object id = new Object();
managerControl.expectAndReturn(manager.getReference(Number.class, id), reference);
managerControl.replay();
factoryControl.replay();
given(manager.getReference(Number.class, id)).willReturn(reference);
assertSame(reference, template.getReference(Number.class, id));
managerControl.verify();
factoryControl.verify();
}
/*
* Test method for
* 'org.springframework.orm.jpa.JpaTemplate.contains(Object)'
*/
@Test
public void testContains() {
boolean result = true;
Object entity = new Object();
managerControl.expectAndReturn(manager.contains(entity), result);
managerControl.replay();
factoryControl.replay();
given(manager.contains(entity)).willReturn(result);
assertSame(result, template.contains(entity));
managerControl.verify();
factoryControl.verify();
}
/*
* Test method for 'org.springframework.orm.jpa.JpaTemplate.refresh(Object)'
*/
@Test
public void testRefresh() {
Object entity = new Object();
manager.refresh(entity);
managerControl.replay();
factoryControl.replay();
template.refresh(entity);
managerControl.verify();
factoryControl.verify();
verify(manager).refresh(entity);
}
/*
* Test method for 'org.springframework.orm.jpa.JpaTemplate.persist(Object)'
*/
@Test
public void testPersist() {
Object entity = new Object();
manager.persist(entity);
managerControl.replay();
factoryControl.replay();
template.persist(entity);
managerControl.verify();
factoryControl.verify();
verify(manager).persist(entity);
}
/*
* Test method for 'org.springframework.orm.jpa.JpaTemplate.merge(T) <T>'
*/
@Test
public void testMerge() {
Object result = new Object();
Object entity = new Object();
managerControl.expectAndReturn(manager.merge(entity), result);
managerControl.replay();
factoryControl.replay();
given(manager.merge(entity)).willReturn(result);
assertSame(result, template.merge(entity));
managerControl.verify();
factoryControl.verify();
}
/*
* Test method for 'org.springframework.orm.jpa.JpaTemplate.remove(Object)'
*/
@Test
public void testRemove() {
Object entity = new Object();
manager.remove(entity);
managerControl.replay();
factoryControl.replay();
template.remove(entity);
managerControl.verify();
factoryControl.verify();
verify(manager).remove(entity);
}
/*
* Test method for 'org.springframework.orm.jpa.JpaTemplate.flush()'
*/
@Test
public void testFlush() {
manager.flush();
managerControl.replay();
factoryControl.replay();
template.flush();
managerControl.verify();
factoryControl.verify();
verify(manager).flush();
}
/*
* Test method for 'org.springframework.orm.jpa.JpaTemplate.find(String)'
*/
@Test
public void testFindString() {
String queryString = "some query";
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
Query query = mock(Query.class);
List result = new ArrayList();
managerControl.expectAndReturn(manager.createQuery(queryString), query);
queryControl.expectAndReturn(query.getResultList(), result);
managerControl.replay();
factoryControl.replay();
queryControl.replay();
given(manager.createQuery(queryString)).willReturn(query);
given(query.getResultList()).willReturn(result);
assertSame(result, template.find(queryString));
managerControl.verify();
factoryControl.verify();
queryControl.verify();
}
/*
* Test method for 'org.springframework.orm.jpa.JpaTemplate.find(String,
* Object...)'
*/
@Test
public void testFindStringObjectArray() {
String queryString = "some query";
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
Query query = mock(Query.class);
List result = new ArrayList();
Object param1 = new Object();
Object param2 = new Object();
Object[] params = new Object[] { param1, param2 };
managerControl.expectAndReturn(manager.createQuery(queryString), query);
queryControl.expectAndReturn(query.setParameter(1, param1), null);
queryControl.expectAndReturn(query.setParameter(2, param2), null);
queryControl.expectAndReturn(query.getResultList(), result);
managerControl.replay();
factoryControl.replay();
queryControl.replay();
given(manager.createQuery(queryString)).willReturn(query);
given(query.getResultList()).willReturn(result);
assertSame(result, template.find(queryString, params));
managerControl.verify();
factoryControl.verify();
queryControl.verify();
verify(query).setParameter(1, param1);
verify(query).setParameter(2, param2);
}
/*
* Test method for 'org.springframework.orm.jpa.JpaTemplate.find(String, Map<String,
* Object>)'
*/
@Test
public void testFindStringMapOfStringObject() {
String queryString = "some query";
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
Query query = mock(Query.class);
List result = new ArrayList();
Object param1 = new Object();
Object param2 = new Object();
@@ -418,46 +343,29 @@ public class JpaTemplateTests extends TestCase {
params.put("param1", param1);
params.put("param2", param2);
managerControl.expectAndReturn(manager.createQuery(queryString), query);
queryControl.expectAndReturn(query.setParameter("param1", param1), null);
queryControl.expectAndReturn(query.setParameter("param2", param2), null);
queryControl.expectAndReturn(query.getResultList(), result);
managerControl.replay();
factoryControl.replay();
queryControl.replay();
given(manager.createQuery(queryString)).willReturn(query);
given(query.getResultList()).willReturn(result);
assertSame(result, template.findByNamedParams(queryString, params));
managerControl.verify();
factoryControl.verify();
queryControl.verify();
verify(query).setParameter("param1", param1);
verify(query).setParameter("param2", param2);
}
/*
* Test method for
* 'org.springframework.orm.jpa.JpaTemplate.findByNamedQuery(String)'
*/
@Test
public void testFindByNamedQueryString() {
String queryName = "some query name";
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
Query query = mock(Query.class);
List result = new ArrayList();
managerControl.expectAndReturn(manager.createNamedQuery(queryName), query);
queryControl.expectAndReturn(query.getResultList(), result);
managerControl.replay();
factoryControl.replay();
queryControl.replay();
given(manager.createNamedQuery(queryName)).willReturn(query);
given(query.getResultList()).willReturn(result);
assertSame(result, template.findByNamedQuery(queryName));
managerControl.verify();
factoryControl.verify();
queryControl.verify();
}
/*
@@ -465,30 +373,22 @@ public class JpaTemplateTests extends TestCase {
* 'org.springframework.orm.jpa.JpaTemplate.findByNamedQuery(String,
* Object...)'
*/
@Test
public void testFindByNamedQueryStringObjectArray() {
String queryName = "some query name";
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
Query query = mock(Query.class);
List result = new ArrayList();
Object param1 = new Object();
Object param2 = new Object();
Object[] params = new Object[] { param1, param2 };
managerControl.expectAndReturn(manager.createNamedQuery(queryName), query);
queryControl.expectAndReturn(query.setParameter(1, param1), null);
queryControl.expectAndReturn(query.setParameter(2, param2), null);
queryControl.expectAndReturn(query.getResultList(), result);
managerControl.replay();
factoryControl.replay();
queryControl.replay();
given(manager.createNamedQuery(queryName)).willReturn(query);
given(query.getResultList()).willReturn(result);
assertSame(result, template.findByNamedQuery(queryName, params));
managerControl.verify();
factoryControl.verify();
queryControl.verify();
verify(query).setParameter(1, param1);
verify(query).setParameter(2, param2);
}
/*
@@ -496,10 +396,10 @@ public class JpaTemplateTests extends TestCase {
* 'org.springframework.orm.jpa.JpaTemplate.findByNamedQuery(String, Map<String,
* Object>)'
*/
@Test
public void testFindByNamedQueryStringMapOfStringObject() {
String queryName = "some query name";
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
Query query = mock(Query.class);
List result = new ArrayList();
Object param1 = new Object();
Object param2 = new Object();
@@ -507,21 +407,11 @@ public class JpaTemplateTests extends TestCase {
params.put("param1", param1);
params.put("param2", param2);
managerControl.expectAndReturn(manager.createNamedQuery(queryName), query);
queryControl.expectAndReturn(query.setParameter("param1", param1), null);
queryControl.expectAndReturn(query.setParameter("param2", param2), null);
queryControl.expectAndReturn(query.getResultList(), result);
managerControl.replay();
factoryControl.replay();
queryControl.replay();
given(manager.createNamedQuery(queryName)).willReturn(query);
given(query.getResultList()).willReturn(result);
assertSame(result, template.findByNamedQueryAndNamedParams(queryName, params));
managerControl.verify();
factoryControl.verify();
queryControl.verify();
verify(query).setParameter("param1", param1);
verify(query).setParameter("param2", param2);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,9 +16,21 @@
package org.springframework.orm.jpa;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
@@ -26,9 +38,9 @@ import javax.persistence.PersistenceException;
import javax.persistence.RollbackException;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.transaction.InvalidIsolationLevelException;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
@@ -42,10 +54,9 @@ import org.springframework.transaction.support.TransactionTemplate;
/**
* @author Costin Leau
* @author Juergen Hoeller
* @author Phillip Webb
*/
public class JpaTransactionManagerTests extends TestCase {
private MockControl factoryControl, managerControl, txControl;
public class JpaTransactionManagerTests {
private EntityManager manager;
@@ -60,46 +71,33 @@ public class JpaTransactionManagerTests extends TestCase {
private TransactionTemplate tt;
@Override
protected void setUp() throws Exception {
factoryControl = MockControl.createControl(EntityManagerFactory.class);
factory = (EntityManagerFactory) factoryControl.getMock();
managerControl = MockControl.createControl(EntityManager.class);
manager = (EntityManager) managerControl.getMock();
txControl = MockControl.createControl(EntityTransaction.class);
tx = (EntityTransaction) txControl.getMock();
@Before
public void setUp() throws Exception {
factory = mock(EntityManagerFactory.class);
manager = mock(EntityManager.class);
tx = mock(EntityTransaction.class);
transactionManager = new JpaTransactionManager(factory);
template = new JpaTemplate(factory);
template.afterPropertiesSet();
tt = new TransactionTemplate(transactionManager);
factoryControl.expectAndReturn(factory.createEntityManager(), manager);
managerControl.expectAndReturn(manager.getTransaction(), tx);
tx.begin();
managerControl.expectAndReturn(manager.isOpen(), true);
manager.close();
given(factory.createEntityManager()).willReturn(manager);
given(manager.getTransaction()).willReturn(tx);
given(manager.isOpen()).willReturn(true);
}
@Override
protected void tearDown() throws Exception {
@After
public void tearDown() throws Exception {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
}
@Test
public void testTransactionCommit() {
managerControl.expectAndReturn(manager.getTransaction(), tx);
txControl.expectAndReturn(tx.getRollbackOnly(), false);
managerControl.expectAndReturn(manager.getTransaction(), tx);
tx.commit();
manager.flush();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.getTransaction()).willReturn(tx);
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -125,22 +123,16 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(tx).commit();
verify(manager).flush();
verify(manager).close();
}
@Test
public void testTransactionCommitWithRollbackException() {
managerControl.expectAndReturn(manager.getTransaction(), tx);
txControl.expectAndReturn(tx.getRollbackOnly(), true);
managerControl.expectAndReturn(manager.getTransaction(), tx);
tx.commit();
txControl.setThrowable(new RollbackException());
manager.flush();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.getTransaction()).willReturn(tx);
given(tx.getRollbackOnly()).willReturn(true);
willThrow(new RollbackException()).given(tx).commit();
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -172,19 +164,14 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(manager).flush();
verify(manager).close();
}
@Test
public void testTransactionRollback() {
managerControl.expectAndReturn(manager.getTransaction(), tx);
txControl.expectAndReturn(tx.isActive(), true);
tx.rollback();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.getTransaction()).willReturn(tx);
given(tx.isActive()).willReturn(true);
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -215,19 +202,13 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(tx).rollback();
verify(manager).close();
}
@Test
public void testTransactionRollbackWithAlreadyRolledBack() {
managerControl.expectAndReturn(manager.getTransaction(), tx);
txControl.expectAndReturn(tx.isActive(), false);
// tx.rollback();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.getTransaction()).willReturn(tx);
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -257,20 +238,13 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(manager).close();
}
@Test
public void testTransactionRollbackOnly() {
managerControl.expectAndReturn(manager.getTransaction(), tx);
txControl.expectAndReturn(tx.isActive(), true);
manager.flush();
tx.rollback();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.getTransaction()).willReturn(tx);
given(tx.isActive()).willReturn(true);
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -299,18 +273,14 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(manager).flush();
verify(tx).rollback();
verify(manager).close();
}
@Test
public void testParticipatingTransactionWithCommit() {
managerControl.expectAndReturn(manager.getTransaction(), tx, 2);
manager.flush();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.getTransaction()).willReturn(tx);
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -321,11 +291,6 @@ public class JpaTransactionManagerTests extends TestCase {
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
txControl.reset();
txControl.expectAndReturn(tx.getRollbackOnly(), false);
tx.commit();
txControl.replay();
assertTrue(TransactionSynchronizationManager.hasResource(factory));
return tt.execute(new TransactionCallback() {
@@ -347,16 +312,15 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(manager).flush();
verify(tx).commit();
verify(manager).close();
}
@Test
public void testParticipatingTransactionWithRollback() {
managerControl.expectAndReturn(manager.getTransaction(), tx, 2);
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.getTransaction()).willReturn(tx);
given(tx.isActive()).willReturn(true);
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -368,12 +332,6 @@ public class JpaTransactionManagerTests extends TestCase {
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
txControl.reset();
txControl.expectAndReturn(tx.isActive(), true, 2);
tx.setRollbackOnly();
tx.rollback();
txControl.replay();
assertTrue(TransactionSynchronizationManager.hasResource(factory));
return tt.execute(new TransactionCallback() {
@Override
@@ -397,18 +355,17 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(tx).setRollbackOnly();
verify(tx).rollback();
verify(manager).close();
}
@Test
public void testParticipatingTransactionWithRollbackOnly() {
managerControl.expectAndReturn(manager.getTransaction(), tx, 3);
manager.flush();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.getTransaction()).willReturn(tx);
given(tx.isActive()).willReturn(true);
given(tx.getRollbackOnly()).willReturn(true);
willThrow(new RollbackException()).given(tx).commit();
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -420,14 +377,6 @@ public class JpaTransactionManagerTests extends TestCase {
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
txControl.reset();
txControl.expectAndReturn(tx.isActive(), true);
tx.setRollbackOnly();
txControl.expectAndReturn(tx.getRollbackOnly(), true);
tx.commit();
txControl.setThrowable(new RollbackException());
txControl.replay();
assertTrue(TransactionSynchronizationManager.hasResource(factory));
return tt.execute(new TransactionCallback() {
@@ -458,23 +407,18 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(manager).flush();
verify(tx).setRollbackOnly();
verify(manager).close();
}
@Test
public void testParticipatingTransactionWithRequiresNew() {
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
factoryControl.expectAndReturn(factory.createEntityManager(), manager);
managerControl.expectAndReturn(manager.getTransaction(), tx, 5);
manager.flush();
managerControl.expectAndReturn(manager.isOpen(), true);
manager.close();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(factory.createEntityManager()).willReturn(manager);
given(manager.getTransaction()).willReturn(tx);
given(manager.isOpen()).willReturn(true);
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -485,17 +429,6 @@ public class JpaTransactionManagerTests extends TestCase {
Object result = tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
txControl.verify();
txControl.reset();
tx.begin();
txControl.expectAndReturn(tx.getRollbackOnly(), false);
tx.commit();
txControl.expectAndReturn(tx.getRollbackOnly(), false);
tx.commit();
txControl.replay();
assertTrue(TransactionSynchronizationManager.hasResource(factory));
return tt.execute(new TransactionCallback() {
@Override
@@ -516,20 +449,16 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(manager).flush();
verify(manager, times(2)).close();
verify(tx, times(2)).begin();
}
@Test
public void testParticipatingTransactionWithRequiresNewAndPrebound() {
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
managerControl.expectAndReturn(manager.getTransaction(), tx, 5);
manager.flush();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.getTransaction()).willReturn(tx);
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -543,17 +472,6 @@ public class JpaTransactionManagerTests extends TestCase {
Object result = tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
txControl.verify();
txControl.reset();
tx.begin();
txControl.expectAndReturn(tx.getRollbackOnly(), false);
tx.commit();
txControl.expectAndReturn(tx.getRollbackOnly(), false);
tx.commit();
txControl.replay();
JpaTemplate template2 = new JpaTemplate(factory);
template2.execute(new JpaCallback() {
@Override
@@ -586,22 +504,17 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(tx, times(2)).begin();
verify(tx, times(2)).commit();
verify(manager).flush();
verify(manager).close();
}
@Test
public void testPropagationSupportsAndRequiresNew() {
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
manager.flush();
managerControl.expectAndReturn(manager.getTransaction(), tx, 2);
txControl.expectAndReturn(tx.getRollbackOnly(), false);
tx.commit();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.getTransaction()).willReturn(tx);
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -634,25 +547,18 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(tx).commit();
verify(manager).flush();
verify(manager).close();
}
@Test
public void testPropagationSupportsAndRequiresNewAndEarlyAccess() {
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
factoryControl.expectAndReturn(factory.createEntityManager(), manager);
managerControl.expectAndReturn(manager.getTransaction(), tx, 2);
manager.flush();
managerControl.expectAndReturn(manager.isOpen(), true);
manager.close();
txControl.expectAndReturn(tx.getRollbackOnly(), false);
tx.commit();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(factory.createEntityManager()).willReturn(manager);
given(manager.getTransaction()).willReturn(tx);
given(manager.isOpen()).willReturn(true);
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -693,37 +599,22 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(tx).commit();
verify(manager).flush();
verify(manager, times(2)).close();
}
@Test
public void testTransactionWithRequiresNewInAfterCompletion() {
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
MockControl managerControl2 = MockControl.createControl(EntityManager.class);
EntityManager manager2 = (EntityManager) managerControl2.getMock();
MockControl txControl2 = MockControl.createControl(EntityTransaction.class);
EntityTransaction tx2 = (EntityTransaction) txControl2.getMock();
EntityManager manager2 = mock(EntityManager.class);
EntityTransaction tx2 = mock(EntityTransaction.class);
managerControl.expectAndReturn(manager.getTransaction(), tx, 2);
factoryControl.expectAndReturn(factory.createEntityManager(), manager2);
managerControl2.expectAndReturn(manager2.getTransaction(), tx2, 3);
txControl.expectAndReturn(tx.getRollbackOnly(), false);
txControl2.expectAndReturn(tx2.getRollbackOnly(), false);
manager.flush();
tx.commit();
tx2.begin();
tx2.commit();
manager2.flush();
managerControl2.expectAndReturn(manager2.isOpen(), true);
manager2.close();
factoryControl.replay();
managerControl.replay();
txControl.replay();
managerControl2.replay();
txControl2.replay();
given(manager.getTransaction()).willReturn(tx);
given(factory.createEntityManager()).willReturn(manager, manager2);
given(manager2.getTransaction()).willReturn(tx2);
given(manager2.isOpen()).willReturn(true);
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
@@ -762,24 +653,18 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
managerControl2.verify();
txControl2.verify();
verify(tx).commit();
verify(tx2).begin();
verify(tx2).commit();
verify(manager).flush();
verify(manager).close();
verify(manager2).flush();
verify(manager2).close();
}
@Test
public void testTransactionCommitWithPropagationSupports() {
managerControl.reset();
txControl.reset();
manager.flush();
managerControl.expectAndReturn(manager.isOpen(), true);
manager.close();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.isOpen()).willReturn(true);
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -809,22 +694,13 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(manager).flush();
verify(manager).close();
}
@Test
public void testTransactionRollbackWithPropagationSupports() {
managerControl.reset();
txControl.reset();
manager.flush();
managerControl.expectAndReturn(manager.isOpen(), true);
manager.close();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.isOpen()).willReturn(true);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
@@ -852,24 +728,13 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(manager).flush();
verify(manager).close();
}
@Test
public void testTransactionCommitWithPrebound() {
factoryControl.reset();
managerControl.reset();
txControl.reset();
managerControl.expectAndReturn(manager.getTransaction(), tx, 3);
tx.begin();
txControl.expectAndReturn(tx.getRollbackOnly(), false);
tx.commit();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.getTransaction()).willReturn(tx);
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -901,25 +766,15 @@ public class JpaTransactionManagerTests extends TestCase {
TransactionSynchronizationManager.unbindResource(factory);
}
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(tx).begin();
verify(tx).commit();
}
@Test
public void testTransactionRollbackWithPrebound() {
factoryControl.reset();
managerControl.reset();
txControl.reset();
managerControl.expectAndReturn(manager.getTransaction(), tx, 2);
tx.begin();
txControl.expectAndReturn(tx.isActive(), true);
tx.rollback();
manager.clear();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.getTransaction()).willReturn(tx);
given(tx.isActive()).willReturn(true);
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
@@ -949,22 +804,13 @@ public class JpaTransactionManagerTests extends TestCase {
TransactionSynchronizationManager.unbindResource(factory);
}
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(tx).begin();
verify(tx).rollback();
verify(manager).clear();
}
@Test
public void testTransactionCommitWithPreboundAndPropagationSupports() {
factoryControl.reset();
managerControl.reset();
txControl.reset();
manager.joinTransaction();
manager.flush();
factoryControl.replay();
managerControl.replay();
txControl.replay();
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -1000,23 +846,12 @@ public class JpaTransactionManagerTests extends TestCase {
TransactionSynchronizationManager.unbindResource(factory);
}
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(manager).joinTransaction();
verify(manager).flush();
}
@Test
public void testTransactionRollbackWithPreboundAndPropagationSupports() {
factoryControl.reset();
managerControl.reset();
txControl.reset();
manager.joinTransaction();
manager.flush();
manager.clear();
factoryControl.replay();
managerControl.replay();
txControl.replay();
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
@@ -1050,26 +885,17 @@ public class JpaTransactionManagerTests extends TestCase {
TransactionSynchronizationManager.unbindResource(factory);
}
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(manager).joinTransaction();
verify(manager).flush();
verify(manager).clear();
}
@Test
public void testTransactionCommitWithDataSource() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
DataSource ds = mock(DataSource.class);
transactionManager.setDataSource(ds);
managerControl.expectAndReturn(manager.getTransaction(), tx);
managerControl.expectAndReturn(manager.getTransaction(), tx);
txControl.expectAndReturn(tx.getRollbackOnly(), false);
tx.commit();
manager.flush();
factoryControl.replay();
managerControl.replay();
txControl.replay();
dsControl.replay();
given(manager.getTransaction()).willReturn(tx);
final List<String> l = new ArrayList<String>();
l.add("test");
@@ -1097,23 +923,16 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
dsControl.verify();
verify(tx).commit();
verify(manager).flush();
verify(manager).close();
}
@Test
public void testInvalidIsolation() {
tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
txControl.reset();
managerControl.reset();
managerControl.expectAndReturn(manager.isOpen(), true);
manager.close();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.isOpen()).willReturn(true);
try {
tt.execute(new TransactionCallbackWithoutResult() {
@@ -1127,21 +946,12 @@ public class JpaTransactionManagerTests extends TestCase {
// expected
}
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(manager).close();
}
@Test
public void testTransactionFlush() {
managerControl.expectAndReturn(manager.getTransaction(), tx);
txControl.expectAndReturn(tx.getRollbackOnly(), false);
managerControl.expectAndReturn(manager.getTransaction(), tx);
tx.commit();
manager.flush();
factoryControl.replay();
managerControl.replay();
txControl.replay();
given(manager.getTransaction()).willReturn(tx);
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
@@ -1157,9 +967,9 @@ public class JpaTransactionManagerTests extends TestCase {
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
factoryControl.verify();
managerControl.verify();
txControl.verify();
verify(tx).commit();
verify(manager).flush();
verify(manager).close();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,22 @@
package org.springframework.orm.jpa;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.util.Map;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
@@ -27,8 +41,7 @@ import javax.persistence.spi.PersistenceProvider;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.OptimisticLockingFailureException;
@@ -41,6 +54,7 @@ import org.springframework.util.SerializationTestUtils;
/**
* @author Rod Johnson
* @author Juergen Hoeller
* @author Phillip Webb
*/
public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityManagerFactoryBeanTests {
@@ -51,13 +65,15 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM
private static PersistenceUnitInfo actualPui;
@Test
public void testValidPersistenceUnit() throws Exception {
parseValidPersistenceUnit();
}
@Test
public void testExceptionTranslationWithNoDialect() throws Exception {
LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
EntityManagerFactory emf = cefb.getObject();
cefb.getObject();
assertNull("No dialect set", cefb.getJpaDialect());
RuntimeException in1 = new RuntimeException("in1");
@@ -68,6 +84,7 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM
assertSame(in2, dex.getCause());
}
@Test
public void testEntityManagerFactoryIsProxied() throws Exception {
LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
EntityManagerFactory emf = cefb.getObject();
@@ -84,21 +101,12 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM
assertNotNull(SerializationTestUtils.serializeAndDeserialize(emf));
}
@Test
public void testApplicationManagedEntityManagerWithoutTransaction() throws Exception {
Object testEntity = new Object();
EntityManager mockEm = mock(EntityManager.class);
MockControl emMc = MockControl.createControl(EntityManager.class);
EntityManager mockEm = (EntityManager) emMc.getMock();
mockEm.contains(testEntity);
emMc.setReturnValue(false);
emMc.replay();
// finish recording mock calls
mockEmf.createEntityManager();
emfMc.setReturnValue(mockEm);
mockEmf.close();
emfMc.setVoidCallable();
emfMc.replay();
given(mockEmf.createEntityManager()).willReturn(mockEm);
LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
EntityManagerFactory emf = cefb.getObject();
@@ -110,48 +118,24 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM
cefb.destroy();
emfMc.verify();
emMc.verify();
verify(mockEmf).close();
}
@Test
public void testApplicationManagedEntityManagerWithTransaction() throws Exception {
Object testEntity = new Object();
MockControl tmMc = MockControl.createControl(EntityTransaction.class);
EntityTransaction mockTx = (EntityTransaction) tmMc.getMock();
mockTx.isActive();
tmMc.setReturnValue(false);
mockTx.begin();
tmMc.setVoidCallable();
mockTx.commit();
tmMc.setVoidCallable();
tmMc.replay();
EntityTransaction mockTx = mock(EntityTransaction.class);
// This one's for the tx (shared)
MockControl sharedEmMc = MockControl.createControl(EntityManager.class);
EntityManager sharedEm = (EntityManager) sharedEmMc.getMock();
sharedEm.getTransaction();
sharedEmMc.setReturnValue(new NoOpEntityTransaction(), 3);
sharedEm.close();
sharedEmMc.setVoidCallable();
sharedEmMc.replay();
mockEmf.createEntityManager();
emfMc.setReturnValue(sharedEm);
EntityManager sharedEm = mock(EntityManager.class);
given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());
// This is the application-specific one
MockControl emMc = MockControl.createControl(EntityManager.class);
EntityManager mockEm = (EntityManager) emMc.getMock();
mockEm.getTransaction();
emMc.setReturnValue(mockTx, 3);
mockEm.contains(testEntity);
emMc.setReturnValue(false);
emMc.replay();
EntityManager mockEm = mock(EntityManager.class);
given(mockEm.getTransaction()).willReturn(mockTx);
mockEmf.createEntityManager();
emfMc.setReturnValue(mockEm);
mockEmf.close();
emfMc.setVoidCallable();
emfMc.replay();
given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);
LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
@@ -172,49 +156,28 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM
cefb.destroy();
emfMc.verify();
emMc.verify();
tmMc.verify();
verify(mockTx).begin();
verify(mockTx).commit();
verify(mockEm).contains(testEntity);
verify(mockEmf).close();
}
@Test
public void testApplicationManagedEntityManagerWithTransactionAndCommitException() throws Exception {
Object testEntity = new Object();
MockControl tmMc = MockControl.createControl(EntityTransaction.class);
EntityTransaction mockTx = (EntityTransaction) tmMc.getMock();
mockTx.isActive();
tmMc.setReturnValue(false);
mockTx.begin();
tmMc.setVoidCallable();
mockTx.commit();
tmMc.setThrowable(new OptimisticLockException());
tmMc.replay();
EntityTransaction mockTx = mock(EntityTransaction.class);
willThrow(new OptimisticLockException()).given(mockTx).commit();
// This one's for the tx (shared)
MockControl sharedEmMc = MockControl.createControl(EntityManager.class);
EntityManager sharedEm = (EntityManager) sharedEmMc.getMock();
sharedEm.getTransaction();
sharedEmMc.setReturnValue(new NoOpEntityTransaction(), 3);
sharedEm.close();
sharedEmMc.setVoidCallable();
sharedEmMc.replay();
mockEmf.createEntityManager();
emfMc.setReturnValue(sharedEm);
EntityManager sharedEm = mock(EntityManager.class);
given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());
// This is the application-specific one
MockControl emMc = MockControl.createControl(EntityManager.class);
EntityManager mockEm = (EntityManager) emMc.getMock();
mockEm.getTransaction();
emMc.setReturnValue(mockTx, 3);
mockEm.contains(testEntity);
emMc.setReturnValue(false);
emMc.replay();
EntityManager mockEm = mock(EntityManager.class);
given(mockEm.getTransaction()).willReturn(mockTx);
mockEmf.createEntityManager();
emfMc.setReturnValue(mockEm);
mockEmf.close();
emfMc.setVoidCallable();
emfMc.replay();
given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);
LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
@@ -241,39 +204,23 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM
cefb.destroy();
emfMc.verify();
emMc.verify();
tmMc.verify();
verify(mockTx).begin();
verify(mockEm).contains(testEntity);
verify(mockEmf).close();
}
@Test
public void testApplicationManagedEntityManagerWithJtaTransaction() throws Exception {
Object testEntity = new Object();
// This one's for the tx (shared)
MockControl sharedEmMc = MockControl.createControl(EntityManager.class);
EntityManager sharedEm = (EntityManager) sharedEmMc.getMock();
sharedEm.getTransaction();
sharedEmMc.setReturnValue(new NoOpEntityTransaction(), 3);
sharedEm.close();
sharedEmMc.setVoidCallable(1);
sharedEmMc.replay();
mockEmf.createEntityManager();
emfMc.setReturnValue(sharedEm);
EntityManager sharedEm = mock(EntityManager.class);
given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());
// This is the application-specific one
MockControl emMc = MockControl.createControl(EntityManager.class);
EntityManager mockEm = (EntityManager) emMc.getMock();
mockEm.joinTransaction();
emMc.setVoidCallable(1);
mockEm.contains(testEntity);
emMc.setReturnValue(false);
emMc.replay();
EntityManager mockEm = mock(EntityManager.class);
mockEmf.createEntityManager();
emfMc.setReturnValue(mockEm);
mockEmf.close();
emfMc.setVoidCallable();
emfMc.replay();
given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);
LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
MutablePersistenceUnitInfo pui = ((MutablePersistenceUnitInfo) cefb.getPersistenceUnitInfo());
@@ -296,8 +243,9 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM
cefb.destroy();
emfMc.verify();
emMc.verify();
verify(mockEm).joinTransaction();
verify(mockEm).contains(testEntity);
verify(mockEmf).close();
}
public LocalContainerEntityManagerFactoryBean parseValidPersistenceUnit() throws Exception {
@@ -307,6 +255,7 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM
return emfb;
}
@Test
public void testInvalidPersistenceUnitName() throws Exception {
try {
createEntityManagerFactoryBean("org/springframework/orm/jpa/domain/persistence.xml", null, "call me Bob");
@@ -347,6 +296,7 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM
//emfMc.verify();
}
@Test
public void testRejectsMissingPersistenceUnitInfo() throws Exception {
LocalContainerEntityManagerFactoryBean containerEmfb = new LocalContainerEntityManagerFactoryBean();
String entityManagerName = "call me Bob";

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,10 @@
package org.springframework.orm.jpa;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.verify;
import java.util.Map;
import java.util.Properties;
@@ -23,8 +27,12 @@ import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceProvider;
import javax.persistence.spi.PersistenceUnitInfo;
import org.junit.After;
import org.junit.Test;
/**
* @author Rod Johnson
* @author Phillip Webb
*/
public class LocalEntityManagerFactoryBeanTests extends AbstractEntityManagerFactoryBeanTests {
@@ -34,19 +42,17 @@ public class LocalEntityManagerFactoryBeanTests extends AbstractEntityManagerFac
private static Map actualProps;
@Override
protected void setUp() throws Exception {
super.setUp();
mockEmf.close();
emfMc.setVoidCallable();
emfMc.replay();
@After
public void verifyClosed() throws Exception {
verify(mockEmf).close();
}
@Test
public void testValidUsageWithDefaultProperties() throws Exception {
testValidUsage(null);
}
@Test
public void testValidUsageWithExplicitProperties() throws Exception {
testValidUsage(new Properties());
}
@@ -73,8 +79,6 @@ public class LocalEntityManagerFactoryBeanTests extends AbstractEntityManagerFac
checkInvariants(lemfb);
lemfb.destroy();
emfMc.verify();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,7 +28,7 @@ import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.PersistenceContext;
import org.springframework.beans.TestBean;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.beans.factory.annotation.Configurable;
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,7 +26,7 @@ import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import org.springframework.beans.TestBean;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.beans.factory.annotation.Configurable;
/**

View File

@@ -10,7 +10,7 @@
</persistence-unit>
<persistence-unit name="Test" transaction-type="RESOURCE_LOCAL">
<class>org.springframework.beans.TestBean</class>
<class>org.springframework.tests.sample.beans.TestBean</class>
<exclude-unlisted-classes/>
</persistence-unit>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,17 +19,13 @@ package org.springframework.orm.jpa.openjpa;
import org.junit.Ignore;
/**
* Test that AspectJ weaving (in particular the currently shipped aspects) work with JPA (see SPR-3873 for more details).
* Test that AspectJ weaving (in particular the currently shipped aspects) work with JPA
* (see SPR-3873 for more details).
*
* @author Ramnivas Laddad
* @author Chris Beams
*/
// TODO [SPR-10074] this test causes gradle to hang.
// When run independently e.g. `./gradlew :spring-orm:test -Dtest.single=OpenJpaEntity...`
// it works fine. When run together with all other tests e.g. `./gradlew :spring-orm:test`
// it hangs on the 'testCanSerializeProxies' test method. Note that this test DOES pass in
// Eclipse, even when the entire 'spring-orm' module is run. Run gradle with '-i' to
// get more details when reproducing the hanging test.
@Ignore("this test causes gradle to hang")
@Ignore("This test causes gradle to hang. See SPR-10333.")
public class OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests extends OpenJpaEntityManagerFactoryIntegrationTests {
@Override

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,7 +34,7 @@ import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
import org.springframework.jdbc.datasource.lookup.MapDataSourceLookup;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
import org.springframework.tests.mock.jndi.SimpleNamingContextBuilder;
import static org.junit.Assert.*;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,29 +13,32 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.orm.jpa.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.orm.jpa.JpaTemplate;
/**
* @author Costin Leau
*
* @author Phillip Webb
*/
public class JpaDaoSupportTests extends TestCase {
public class JpaDaoSupportTests {
@Test
public void testJpaDaoSupportWithEntityManager() throws Exception {
MockControl mockControl = MockControl.createControl(EntityManager.class);
EntityManager entityManager = (EntityManager) mockControl.getMock();
mockControl.replay();
EntityManager entityManager = mock(EntityManager.class);
final List test = new ArrayList();
JpaDaoSupport dao = new JpaDaoSupport() {
@Override
@@ -48,13 +51,11 @@ public class JpaDaoSupportTests extends TestCase {
assertNotNull("jpa template not created", dao.getJpaTemplate());
assertEquals("incorrect entity manager", entityManager, dao.getJpaTemplate().getEntityManager());
assertEquals("initDao not called", test.size(), 1);
mockControl.verify();
}
@Test
public void testJpaDaoSupportWithEntityManagerFactory() throws Exception {
MockControl mockControl = MockControl.createControl(EntityManagerFactory.class);
EntityManagerFactory entityManagerFactory = (EntityManagerFactory) mockControl.getMock();
mockControl.replay();
EntityManagerFactory entityManagerFactory = mock(EntityManagerFactory.class);
final List test = new ArrayList();
JpaDaoSupport dao = new JpaDaoSupport() {
@Override
@@ -68,9 +69,9 @@ public class JpaDaoSupportTests extends TestCase {
assertEquals("incorrect entity manager factory", entityManagerFactory,
dao.getJpaTemplate().getEntityManagerFactory());
assertEquals("initDao not called", test.size(), 1);
mockControl.verify();
}
@Test
public void testJpaDaoSupportWithJpaTemplate() throws Exception {
JpaTemplate template = new JpaTemplate();
final List test = new ArrayList();
@@ -87,6 +88,7 @@ public class JpaDaoSupportTests extends TestCase {
assertEquals("initDao not called", test.size(), 1);
}
@Test
public void testInvalidJpaTemplate() throws Exception {
JpaDaoSupport dao = new JpaDaoSupport() {
};

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,13 +16,16 @@
package org.springframework.orm.jpa.support;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.createStrictMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.reset;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.io.IOException;
import java.util.concurrent.Callable;
@@ -35,8 +38,9 @@ import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.mock.web.test.MockFilterConfig;
import org.springframework.mock.web.test.MockHttpServletRequest;
@@ -56,8 +60,9 @@ import org.springframework.web.context.support.StaticWebApplicationContext;
* @author Costin Leau
* @author Juergen Hoeller
* @author Chris Beams
* @author Phillip Webb
*/
public class OpenEntityManagerInViewTests extends TestCase {
public class OpenEntityManagerInViewTests {
private EntityManager manager;
@@ -66,25 +71,26 @@ public class OpenEntityManagerInViewTests extends TestCase {
private JpaTemplate template;
@Override
protected void setUp() throws Exception {
factory = createMock(EntityManagerFactory.class);
manager = createMock(EntityManager.class);
@Before
public void setUp() throws Exception {
factory = mock(EntityManagerFactory.class);
manager = mock(EntityManager.class);
template = new JpaTemplate(factory);
template.afterPropertiesSet();
expect(factory.createEntityManager()).andReturn(manager);
given(factory.createEntityManager()).willReturn(manager);
}
@Override
protected void tearDown() throws Exception {
@After
public void tearDown() throws Exception {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
}
@Test
public void testOpenEntityManagerInViewInterceptor() throws Exception {
OpenEntityManagerInViewInterceptor interceptor = new OpenEntityManagerInViewInterceptor();
interceptor.setEntityManagerFactory(factory);
@@ -92,8 +98,6 @@ public class OpenEntityManagerInViewTests extends TestCase {
MockServletContext sc = new MockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(sc);
replay(manager, factory);
interceptor.preHandle(new ServletWebRequest(request));
assertTrue(TransactionSynchronizationManager.hasResource(factory));
@@ -111,29 +115,18 @@ public class OpenEntityManagerInViewTests extends TestCase {
interceptor.postHandle(new ServletWebRequest(request), null);
interceptor.afterCompletion(new ServletWebRequest(request), null);
verify(manager, factory);
reset(manager, factory);
replay(manager, factory);
interceptor.postHandle(new ServletWebRequest(request), null);
assertTrue(TransactionSynchronizationManager.hasResource(factory));
verify(manager, factory);
reset(manager, factory);
expect(manager.isOpen()).andReturn(true);
manager.close();
replay(manager, factory);
given(manager.isOpen()).willReturn(true);
interceptor.afterCompletion(new ServletWebRequest(request), null);
assertFalse(TransactionSynchronizationManager.hasResource(factory));
verify(manager, factory);
verify(manager).close();
}
@Test
public void testOpenEntityManagerInViewInterceptorAsyncScenario() throws Exception {
// Initial request thread
@@ -145,19 +138,10 @@ public class OpenEntityManagerInViewTests extends TestCase {
MockHttpServletRequest request = new MockHttpServletRequest(sc);
ServletWebRequest webRequest = new ServletWebRequest(request);
replay(manager, factory);
interceptor.preHandle(webRequest);
assertTrue(TransactionSynchronizationManager.hasResource(factory));
verify(manager, factory);
AsyncWebRequest asyncWebRequest = createStrictMock(AsyncWebRequest.class);
asyncWebRequest.addCompletionHandler((Runnable) anyObject());
asyncWebRequest.addTimeoutHandler((Runnable) anyObject());
asyncWebRequest.addCompletionHandler((Runnable) anyObject());
asyncWebRequest.startAsync();
replay(asyncWebRequest);
AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class);
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(webRequest);
asyncManager.setTaskExecutor(new SyncTaskExecutor());
@@ -169,23 +153,19 @@ public class OpenEntityManagerInViewTests extends TestCase {
}
});
verify(asyncWebRequest);
verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class));
verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
verify(asyncWebRequest).startAsync();
interceptor.afterConcurrentHandlingStarted(webRequest);
assertFalse(TransactionSynchronizationManager.hasResource(factory));
// Async dispatch thread
reset(manager, factory);
replay(manager, factory);
interceptor.preHandle(webRequest);
assertTrue(TransactionSynchronizationManager.hasResource(factory));
verify(manager, factory);
reset(manager, factory);
replay(manager, factory);
asyncManager.clearConcurrentResult();
// check that further invocations simply participate
@@ -202,41 +182,26 @@ public class OpenEntityManagerInViewTests extends TestCase {
interceptor.postHandle(new ServletWebRequest(request), null);
interceptor.afterCompletion(new ServletWebRequest(request), null);
verify(manager, factory);
reset(manager, factory);
replay(manager, factory);
interceptor.postHandle(webRequest, null);
assertTrue(TransactionSynchronizationManager.hasResource(factory));
verify(manager, factory);
reset(manager, factory);
expect(manager.isOpen()).andReturn(true);
manager.close();
replay(manager, factory);
given(manager.isOpen()).willReturn(true);
interceptor.afterCompletion(webRequest, null);
assertFalse(TransactionSynchronizationManager.hasResource(factory));
verify(manager, factory);
verify(manager).close();
}
@Test
public void testOpenEntityManagerInViewFilter() throws Exception {
expect(manager.isOpen()).andReturn(true);
manager.close();
given(manager.isOpen()).willReturn(true);
replay(manager, factory);
final EntityManagerFactory factory2 = mock(EntityManagerFactory.class);
final EntityManager manager2 = mock(EntityManager.class);
final EntityManagerFactory factory2 = createMock(EntityManagerFactory.class);
final EntityManager manager2 = createMock(EntityManager.class);
expect(factory2.createEntityManager()).andReturn(manager2);
expect(manager2.isOpen()).andReturn(true);
manager2.close();
replay(factory2, manager2);
given(factory2.createEntityManager()).willReturn(manager2);
given(manager2.isOpen()).willReturn(true);
MockServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
@@ -283,26 +248,21 @@ public class OpenEntityManagerInViewTests extends TestCase {
assertFalse(TransactionSynchronizationManager.hasResource(factory2));
assertNotNull(request.getAttribute("invoked"));
verify(manager, factory);
verify(factory2, manager2);
verify(manager).close();
verify(manager2).close();
wac.close();
}
@Test
public void testOpenEntityManagerInViewFilterAsyncScenario() throws Exception {
expect(manager.isOpen()).andReturn(true);
manager.close();
given(manager.isOpen()).willReturn(true);
replay(manager, factory);
final EntityManagerFactory factory2 = mock(EntityManagerFactory.class);
final EntityManager manager2 = mock(EntityManager.class);
final EntityManagerFactory factory2 = createMock(EntityManagerFactory.class);
final EntityManager manager2 = createMock(EntityManager.class);
expect(factory2.createEntityManager()).andReturn(manager2);
expect(manager2.isOpen()).andReturn(true);
manager2.close();
replay(factory2, manager2);
given(factory2.createEntityManager()).willReturn(manager2);
given(manager2.isOpen()).willReturn(true);
MockServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
@@ -348,13 +308,8 @@ public class OpenEntityManagerInViewTests extends TestCase {
FilterChain filterChain3 = new PassThroughFilterChain(filter2, filterChain2);
AsyncWebRequest asyncWebRequest = createMock(AsyncWebRequest.class);
asyncWebRequest.addCompletionHandler((Runnable) anyObject());
asyncWebRequest.addTimeoutHandler((Runnable) anyObject());
asyncWebRequest.addCompletionHandler((Runnable) anyObject());
asyncWebRequest.startAsync();
expect(asyncWebRequest.isAsyncStarted()).andReturn(true).anyTimes();
replay(asyncWebRequest);
AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class);
given(asyncWebRequest.isAsyncStarted()).willReturn(true);
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
asyncManager.setTaskExecutor(new SyncTaskExecutor());
@@ -375,11 +330,15 @@ public class OpenEntityManagerInViewTests extends TestCase {
assertEquals(1, count2.get());
assertNotNull(request.getAttribute("invoked"));
verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class));
verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
verify(asyncWebRequest).startAsync();
// Async dispatch after concurrent handling produces result ...
reset(asyncWebRequest);
expect(asyncWebRequest.isAsyncStarted()).andReturn(false).anyTimes();
replay(asyncWebRequest);
given(asyncWebRequest.isAsyncStarted()).willReturn(false);
assertFalse(TransactionSynchronizationManager.hasResource(factory));
assertFalse(TransactionSynchronizationManager.hasResource(factory2));
@@ -389,8 +348,8 @@ public class OpenEntityManagerInViewTests extends TestCase {
assertEquals(2, count.get());
assertEquals(2, count2.get());
verify(manager, factory);
verify(factory2, manager2);
verify(manager).close();
verify(manager2).close();
wac.close();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,15 @@
package org.springframework.orm.jpa.support;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.withSettings;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
@@ -23,6 +32,7 @@ import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
@@ -30,21 +40,20 @@ import javax.persistence.PersistenceContextType;
import javax.persistence.PersistenceProperty;
import javax.persistence.PersistenceUnit;
import org.easymock.MockControl;
import org.hibernate.ejb.HibernateEntityManager;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.SimpleMapScope;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.mock.jndi.ExpectedLookupTemplate;
import org.springframework.orm.jpa.AbstractEntityManagerFactoryBeanTests;
import org.springframework.orm.jpa.DefaultJpaDialect;
import org.springframework.orm.jpa.EntityManagerFactoryInfo;
import org.springframework.orm.jpa.EntityManagerHolder;
import org.springframework.stereotype.Repository;
import org.springframework.tests.context.SimpleMapScope;
import org.springframework.tests.mock.jndi.ExpectedLookupTemplate;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.SerializationTestUtils;
@@ -53,10 +62,13 @@ import org.springframework.util.SerializationTestUtils;
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Phillip Webb
*/
public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanTests {
@Test
public void testPrivatePersistenceContextField() throws Exception {
mockEmf = mock(EntityManagerFactory.class, withSettings().serializable());
GenericApplicationContext gac = new GenericApplicationContext();
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
gac.registerBeanDefinition("annotationProcessor",
@@ -78,6 +90,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean2.em));
}
@Test
public void testPrivateVendorSpecificPersistenceContextField() {
GenericApplicationContext gac = new GenericApplicationContext();
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
@@ -92,11 +105,10 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
assertNotNull(bean.em);
}
@Test
public void testPublicExtendedPersistenceContextSetter() throws Exception {
EntityManager mockEm = MockControl.createControl(EntityManager.class).getMock();
mockEmf.createEntityManager();
emfMc.setReturnValue(mockEm, 1);
emfMc.replay();
EntityManager mockEm = mock(EntityManager.class);
given(mockEmf.createEntityManager()).willReturn(mockEm);
GenericApplicationContext gac = new GenericApplicationContext();
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
@@ -109,24 +121,13 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean(
DefaultPublicPersistenceContextSetter.class.getName());
assertNotNull(bean.em);
emfMc.verify();
}
@Test
public void testPublicSpecificExtendedPersistenceContextSetter() throws Exception {
emfMc.replay();
MockControl<EntityManagerFactory> emfMc2 = MockControl.createControl(EntityManagerFactory.class);
EntityManagerFactory mockEmf2 = emfMc2.getMock();
MockControl<EntityManager> emMc2 = MockControl.createControl(EntityManager.class);
EntityManager mockEm2 = emMc2.getMock();
mockEm2.getTransaction();
emMc2.setReturnValue(null, 1);
mockEm2.flush();
emMc2.setVoidCallable(1);
emMc2.replay();
mockEmf2.createEntityManager();
emfMc2.setReturnValue(mockEm2, 1);
emfMc2.replay();
EntityManagerFactory mockEmf2 = mock(EntityManagerFactory.class);
EntityManager mockEm2 = mock(EntityManager.class);
given(mockEmf2.createEntityManager()).willReturn(mockEm2);
GenericApplicationContext gac = new GenericApplicationContext();
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
@@ -141,16 +142,15 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
SpecificPublicPersistenceContextSetter.class.getName());
assertNotNull(bean.getEntityManager());
bean.getEntityManager().flush();
emfMc.verify();
emfMc2.verify();
verify(mockEm2).getTransaction();
verify(mockEm2).flush();
}
@Test
public void testPublicExtendedPersistenceContextSetterWithSerialization() throws Exception {
DummyInvocationHandler ih = new DummyInvocationHandler();
Object mockEm = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] {EntityManager.class}, ih);
mockEmf.createEntityManager();
emfMc.setReturnValue(mockEm, 1);
emfMc.replay();
given(mockEmf.createEntityManager()).willReturn((EntityManager) mockEm);
GenericApplicationContext gac = new GenericApplicationContext();
SimpleMapScope myScope = new SimpleMapScope();
@@ -172,27 +172,19 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
serialized.close();
assertTrue(DummyInvocationHandler.closed);
DummyInvocationHandler.closed = false;
emfMc.verify();
}
@Test
@SuppressWarnings("unchecked")
public void testPublicExtendedPersistenceContextSetterWithEntityManagerInfoAndSerialization() throws Exception {
Object mockEm = Proxy.newProxyInstance(
getClass().getClassLoader(), new Class[] {EntityManager.class}, new DummyInvocationHandler());
MockControl emfMc = MockControl.createControl(EntityManagerFactoryWithInfo.class);
EntityManagerFactoryWithInfo mockEmf = (EntityManagerFactoryWithInfo) emfMc.getMock();
mockEmf.getNativeEntityManagerFactory();
emfMc.setReturnValue(mockEmf);
mockEmf.getPersistenceUnitInfo();
emfMc.setReturnValue(null);
mockEmf.getJpaDialect();
emfMc.setReturnValue(new DefaultJpaDialect());
mockEmf.getEntityManagerInterface();
emfMc.setReturnValue(EntityManager.class);
mockEmf.getBeanClassLoader();
emfMc.setReturnValue(getClass().getClassLoader());
mockEmf.createEntityManager();
emfMc.setReturnValue(mockEm);
emfMc.replay();
EntityManager mockEm = mock(EntityManager.class, withSettings().serializable());
given(mockEm.isOpen()).willReturn(true);
EntityManagerFactoryWithInfo mockEmf = mock(EntityManagerFactoryWithInfo.class);
given(mockEmf.getNativeEntityManagerFactory()).willReturn(mockEmf);
given(mockEmf.getJpaDialect()).willReturn(new DefaultJpaDialect());
given(mockEmf.getEntityManagerInterface()).willReturn((Class)EntityManager.class);
given(mockEmf.getBeanClassLoader()).willReturn(getClass().getClassLoader());
given(mockEmf.createEntityManager()).willReturn(mockEm);
GenericApplicationContext gac = new GenericApplicationContext();
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
@@ -206,11 +198,11 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
DefaultPublicPersistenceContextSetter.class.getName());
assertNotNull(bean.em);
assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean.em));
emfMc.verify();
}
@Test
public void testPublicExtendedPersistenceContextSetterWithOverriding() {
EntityManager mockEm2 = MockControl.createControl(EntityManager.class).getMock();
EntityManager mockEm2 = mock(EntityManager.class);
GenericApplicationContext gac = new GenericApplicationContext();
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
@@ -226,6 +218,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
assertSame(mockEm2, bean.em);
}
@Test
public void testPrivatePersistenceUnitField() {
GenericApplicationContext gac = new GenericApplicationContext();
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
@@ -240,6 +233,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
assertSame(mockEmf, bean.emf);
}
@Test
public void testPublicPersistenceUnitSetter() {
GenericApplicationContext gac = new GenericApplicationContext();
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
@@ -254,9 +248,9 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
assertSame(mockEmf, bean.emf);
}
@Test
public void testPublicPersistenceUnitSetterWithOverriding() {
EntityManagerFactory mockEmf2 =
MockControl.createControl(EntityManagerFactory.class).getMock();
EntityManagerFactory mockEmf2 = mock(EntityManagerFactory.class);
GenericApplicationContext gac = new GenericApplicationContext();
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
@@ -272,9 +266,9 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
assertSame(mockEmf2, bean.emf);
}
@Test
public void testPublicPersistenceUnitSetterWithUnitIdentifiedThroughBeanName() {
EntityManagerFactory mockEmf2 =
MockControl.createControl(EntityManagerFactory.class).getMock();
EntityManagerFactory mockEmf2 = mock(EntityManagerFactory.class);
GenericApplicationContext gac = new GenericApplicationContext();
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
@@ -297,12 +291,10 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
assertSame(mockEmf2, bean2.emf);
}
@Test
public void testPublicPersistenceUnitSetterWithMultipleUnitsIdentifiedThroughUnitName() {
MockControl emf2Mc = MockControl.createControl(EntityManagerFactoryWithInfo.class);
EntityManagerFactoryWithInfo mockEmf2 = (EntityManagerFactoryWithInfo) emf2Mc.getMock();
mockEmf2.getPersistenceUnitName();
emf2Mc.setReturnValue("Person", 2);
emf2Mc.replay();
EntityManagerFactoryWithInfo mockEmf2 = mock(EntityManagerFactoryWithInfo.class);
given(mockEmf2.getPersistenceUnitName()).willReturn("Person");
GenericApplicationContext gac = new GenericApplicationContext();
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
@@ -322,19 +314,14 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
gac.getBean(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName());
assertSame(mockEmf, bean.emf);
assertSame(mockEmf2, bean2.emf);
emf2Mc.verify();
}
@Ignore
public void ignoreTestPersistenceUnitsFromJndi() {
mockEmf.createEntityManager();
Object mockEm = MockControl.createControl(EntityManager.class).getMock();
emfMc.setReturnValue(mockEm, 1);
emfMc.replay();
EntityManager mockEm = mock(EntityManager.class);
given(mockEmf.createEntityManager()).willReturn(mockEm);
MockControl emf2Mc = MockControl.createControl(EntityManagerFactoryWithInfo.class);
EntityManagerFactoryWithInfo mockEmf2 = (EntityManagerFactoryWithInfo) emf2Mc.getMock();
EntityManagerFactoryWithInfo mockEmf2 = mock(EntityManagerFactoryWithInfo.class);
Map<String, String> persistenceUnits = new HashMap<String, String>();
persistenceUnits.put("", "pu1");
@@ -369,13 +356,11 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
assertSame(mockEmf2, bean2.emf);
assertNotNull(bean3.em);
assertNotNull(bean4.em);
emfMc.verify();
}
@Test
public void testPersistenceUnitsFromJndiWithDefaultUnit() {
MockControl emf2Mc = MockControl.createControl(EntityManagerFactoryWithInfo.class);
EntityManagerFactoryWithInfo mockEmf2 = (EntityManagerFactoryWithInfo) emf2Mc.getMock();
EntityManagerFactoryWithInfo mockEmf2 = mock(EntityManagerFactoryWithInfo.class);
Map<String, String> persistenceUnits = new HashMap<String, String>();
persistenceUnits.put("System", "pu1");
@@ -403,6 +388,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
assertSame(mockEmf2, bean2.emf);
}
@Test
public void testSinglePersistenceUnitFromJndi() {
Map<String, String> persistenceUnits = new HashMap<String, String>();
persistenceUnits.put("Person", "pu1");
@@ -427,10 +413,11 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
assertSame(mockEmf, bean2.emf);
}
@Test
public void testPersistenceContextsFromJndi() {
Object mockEm = MockControl.createControl(EntityManager.class).getMock();
Object mockEm2 = MockControl.createControl(EntityManager.class).getMock();
Object mockEm3 = MockControl.createControl(EntityManager.class).getMock();
EntityManager mockEm = mock(EntityManager.class);
EntityManager mockEm2 = mock(EntityManager.class);
EntityManager mockEm3 = mock(EntityManager.class);
Map<String, String> persistenceContexts = new HashMap<String, String>();
persistenceContexts.put("", "pc1");
@@ -466,10 +453,11 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
assertSame(mockEm3, bean3.em);
}
@Test
public void testPersistenceContextsFromJndiWithDefaultUnit() {
Object mockEm = MockControl.createControl(EntityManager.class).getMock();
Object mockEm2 = MockControl.createControl(EntityManager.class).getMock();
Object mockEm3 = MockControl.createControl(EntityManager.class).getMock();
EntityManager mockEm = mock(EntityManager.class);
EntityManager mockEm2 = mock(EntityManager.class);
EntityManager mockEm3 = mock(EntityManager.class);
Map<String, String> persistenceContexts = new HashMap<String, String>();
persistenceContexts.put("System", "pc1");
@@ -506,9 +494,10 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
assertSame(mockEm3, bean3.em);
}
@Test
public void testSinglePersistenceContextFromJndi() {
Object mockEm = MockControl.createControl(EntityManager.class).getMock();
Object mockEm2 = MockControl.createControl(EntityManager.class).getMock();
EntityManager mockEm = mock(EntityManager.class);
EntityManager mockEm2 = mock(EntityManager.class);
Map<String, String> persistenceContexts = new HashMap<String, String>();
persistenceContexts.put("System", "pc1");
@@ -537,6 +526,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
assertSame(mockEm2, bean2.em);
}
@Test
public void testFieldOfWrongTypeAnnotatedWithPersistenceUnit() {
PersistenceAnnotationBeanPostProcessor babpp = new PersistenceAnnotationBeanPostProcessor();
try {
@@ -548,6 +538,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
}
}
@Test
public void testSetterOfWrongTypeAnnotatedWithPersistenceUnit() {
PersistenceAnnotationBeanPostProcessor babpp = new PersistenceAnnotationBeanPostProcessor();
try {
@@ -559,6 +550,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
}
}
@Test
public void testSetterWithNoArgs() {
PersistenceAnnotationBeanPostProcessor babpp = new PersistenceAnnotationBeanPostProcessor();
try {
@@ -572,45 +564,37 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
@Ignore
public void ignoreTestNoPropertiesPassedIn() {
mockEmf.createEntityManager();
emfMc.setReturnValue(MockControl.createControl(EntityManager.class).getMock(), 1);
emfMc.replay();
EntityManager mockEm = mock(EntityManager.class);
given(mockEmf.createEntityManager()).willReturn(mockEm);
PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor();
DefaultPrivatePersistenceContextFieldExtended dppcf = new DefaultPrivatePersistenceContextFieldExtended();
babpp.postProcessAfterInstantiation(dppcf, "bean name does not matter");
assertNotNull(dppcf.em);
emfMc.verify();
}
@Ignore
public void ignoreTestPropertiesPassedIn() {
Properties props = new Properties();
props.put("foo", "bar");
mockEmf.createEntityManager(props);
emfMc.setReturnValue(MockControl.createControl(EntityManager.class).getMock(), 1);
emfMc.replay();
EntityManager mockEm = mock(EntityManager.class);
given(mockEmf.createEntityManager(props)).willReturn(mockEm);
PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor();
DefaultPrivatePersistenceContextFieldExtendedWithProps dppcf =
new DefaultPrivatePersistenceContextFieldExtendedWithProps();
babpp.postProcessAfterInstantiation(dppcf, "bean name does not matter");
assertNotNull(dppcf.em);
emfMc.verify();
}
@Test
public void testPropertiesForTransactionalEntityManager() {
Properties props = new Properties();
props.put("foo", "bar");
MockControl emC = MockControl.createControl(EntityManager.class);
EntityManager em = (EntityManager) emC.getMock();
emfMc.expectAndReturn(mockEmf.createEntityManager(props), em);
emC.expectAndReturn(em.getDelegate(), new Object());
emC.expectAndReturn(em.isOpen(), true);
em.close();
emfMc.replay();
emC.replay();
EntityManager em = mock(EntityManager.class);
given(mockEmf.createEntityManager(props)).willReturn(em);
given(em.getDelegate()).willReturn(new Object());
given(em.isOpen()).willReturn(true);
PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor();
DefaultPrivatePersistenceContextFieldWithProperties transactionalField =
@@ -620,27 +604,22 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
assertNotNull(transactionalField.em);
assertNotNull(transactionalField.em.getDelegate());
emfMc.verify();
emC.verify();
verify(em).close();
}
/**
* Binds an EMF to the thread and tests if EM with different properties
* generate new EMs or not.
*/
@Test
public void testPropertiesForSharedEntityManager1() {
Properties props = new Properties();
props.put("foo", "bar");
MockControl emC = MockControl.createControl(EntityManager.class);
EntityManager em = (EntityManager) emC.getMock();
EntityManager em = mock(EntityManager.class);
// only one call made - the first EM definition wins (in this case the one w/ the properties)
emfMc.expectAndReturn(mockEmf.createEntityManager(props), em);
emC.expectAndReturn(em.getDelegate(), new Object(), 2);
emC.expectAndReturn(em.isOpen(), true);
em.close();
emfMc.replay();
emC.replay();
given(mockEmf.createEntityManager(props)).willReturn(em);
given(em.getDelegate()).willReturn(new Object());
given(em.isOpen()).willReturn(true);
PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor();
DefaultPrivatePersistenceContextFieldWithProperties transactionalFieldWithProperties =
@@ -658,27 +637,22 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
try {
TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(em));
assertNotNull(transactionalField.em.getDelegate());
emfMc.verify();
emC.verify();
verify(em).close();
}
finally {
TransactionSynchronizationManager.unbindResource(mockEmf);
}
}
@Test
public void testPropertiesForSharedEntityManager2() {
Properties props = new Properties();
props.put("foo", "bar");
MockControl emC = MockControl.createControl(EntityManager.class);
EntityManager em = (EntityManager) emC.getMock();
EntityManager em = mock(EntityManager.class);
// only one call made - the first EM definition wins (in this case the one w/o the properties)
emfMc.expectAndReturn(mockEmf.createEntityManager(), em);
emC.expectAndReturn(em.getDelegate(), new Object(), 2);
emC.expectAndReturn(em.isOpen(), true);
em.close();
emfMc.replay();
emC.replay();
given(mockEmf.createEntityManager()).willReturn(em);
given(em.getDelegate()).willReturn(new Object(), 2);
given(em.isOpen()).willReturn(true);
PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor();
DefaultPrivatePersistenceContextFieldWithProperties transactionalFieldWithProperties =
@@ -696,8 +670,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
try {
TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(em));
assertNotNull(transactionalFieldWithProperties.em.getDelegate());
emfMc.verify();
emC.verify();
verify(em).close();
}
finally {
TransactionSynchronizationManager.unbindResource(mockEmf);
@@ -899,5 +872,4 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT
throw new IllegalStateException();
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,13 +16,18 @@
package org.springframework.orm.jpa.support;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.easymock.MockControl;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.orm.jpa.EntityManagerHolder;
import org.springframework.orm.jpa.EntityManagerProxy;
import org.springframework.transaction.support.TransactionSynchronizationManager;
@@ -30,6 +35,7 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
/**
* @author Rod Johnson
* @author Juergen Hoeller
* @author Phillip Webb
*/
public class SharedEntityManagerFactoryTests {
@@ -37,22 +43,11 @@ public class SharedEntityManagerFactoryTests {
public void testValidUsage() {
Object o = new Object();
MockControl emMc = MockControl.createControl(EntityManager.class);
EntityManager mockEm = (EntityManager) emMc.getMock();
EntityManager mockEm = mock(EntityManager.class);
given(mockEm.isOpen()).willReturn(true);
mockEm.contains(o);
emMc.setReturnValue(false, 1);
emMc.expectAndReturn(mockEm.isOpen(), true);
mockEm.close();
emMc.setVoidCallable(1);
emMc.replay();
MockControl emfMc = MockControl.createControl(EntityManagerFactory.class);
EntityManagerFactory mockEmf = (EntityManagerFactory) emfMc.getMock();
mockEmf.createEntityManager();
emfMc.setReturnValue(mockEm, 1);
emfMc.replay();
EntityManagerFactory mockEmf = mock(EntityManagerFactory.class);
given(mockEmf.createEntityManager()).willReturn(mockEm);
SharedEntityManagerBean proxyFactoryBean = new SharedEntityManagerBean();
proxyFactoryBean.setEntityManagerFactory(mockEmf);
@@ -83,10 +78,9 @@ public class SharedEntityManagerFactoryTests {
TransactionSynchronizationManager.unbindResource(mockEmf);
}
emfMc.verify();
emMc.verify();
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
verify(mockEm).contains(o);
verify(mockEm).close();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,9 +26,9 @@ import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrat
* Toplink-specific JPA tests with multiple EntityManagerFactory instances.
*
* @author Costin Leau
* @author Chris Beams
*/
// TODO [SPR-10074] this test causes gradle to hang. See OJEMFWAJWIT.
@Ignore("this test causes gradle to hang. See OJEMFWAJWIT.")
@Ignore("This test causes gradle to hang. See SPR-10333.")
public class TopLinkMultiEntityManagerFactoryIntegrationTests extends
AbstractContainerEntityManagerFactoryIntegrationTests {

View File

@@ -1,67 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.transaction;
import javax.transaction.Status;
import javax.transaction.Synchronization;
import javax.transaction.xa.XAResource;
/**
* @author Juergen Hoeller
* @since 31.08.2004
*/
public class MockJtaTransaction implements javax.transaction.Transaction {
private Synchronization synchronization;
@Override
public int getStatus() {
return Status.STATUS_ACTIVE;
}
@Override
public void registerSynchronization(Synchronization synchronization) {
this.synchronization = synchronization;
}
public Synchronization getSynchronization() {
return synchronization;
}
@Override
public boolean enlistResource(XAResource xaResource) {
return false;
}
@Override
public boolean delistResource(XAResource xaResource, int i) {
return false;
}
@Override
public void commit() {
}
@Override
public void rollback() {
}
@Override
public void setRollbackOnly() {
}
}

View File

@@ -1,97 +0,0 @@
/*
* The Spring Framework is published under the terms
* of the Apache Software License.
*/
package org.springframework.util;
import java.awt.Point;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import junit.framework.TestCase;
import org.springframework.beans.TestBean;
/**
* Utilities for testing serializability of objects.
* Exposes static methods for use in other test cases.
* Extends TestCase only to test itself.
*
* @author Rod Johnson
*/
public class SerializationTestUtils extends TestCase {
public static void testSerialization(Object o) throws IOException {
OutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
}
public static boolean isSerializable(Object o) throws IOException {
try {
testSerialization(o);
return true;
}
catch (NotSerializableException ex) {
return false;
}
}
public static Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.flush();
baos.flush();
byte[] bytes = baos.toByteArray();
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(is);
Object o2 = ois.readObject();
return o2;
}
public SerializationTestUtils(String s) {
super(s);
}
public void testWithNonSerializableObject() throws IOException {
TestBean o = new TestBean();
assertFalse(o instanceof Serializable);
assertFalse(isSerializable(o));
try {
testSerialization(o);
fail();
}
catch (NotSerializableException ex) {
// Ok
}
}
public void testWithSerializableObject() throws Exception {
int x = 5;
int y = 10;
Point p = new Point(x, y);
assertTrue(p instanceof Serializable);
testSerialization(p);
assertTrue(isSerializable(p));
Point p2 = (Point) serializeAndDeserialize(p);
assertNotSame(p, p2);
assertEquals(x, (int) p2.getX());
assertEquals(y, (int) p2.getY());
}
}

View File

@@ -8,13 +8,13 @@
<!-- age should inherit value of 1 from parent -->
</bean>
<bean id="inheritsWithDifferentClass" class="org.springframework.beans.DerivedTestBean"
<bean id="inheritsWithDifferentClass" class="org.springframework.tests.sample.beans.DerivedTestBean"
parent="inheritedTestBean" init-method="initialize">
<property name="name"><value>override</value></property>
<!-- age should inherit value of 1 from parent -->
</bean>
<bean id="inheritsWithClass" class="org.springframework.beans.DerivedTestBean"
<bean id="inheritsWithClass" class="org.springframework.tests.sample.beans.DerivedTestBean"
parent="inheritedTestBeanWithoutClass" init-method="initialize">
<property name="name"><value>override</value></property>
<!-- age should inherit value of 1 from parent -->
@@ -42,7 +42,7 @@
<bean id="bogusParent" parent="bogus" scope="prototype"/>
<bean id="indexedTestBean" class="org.springframework.beans.IndexedTestBean">
<bean id="indexedTestBean" class="org.springframework.tests.sample.beans.IndexedTestBean">
<property name="array[0].name"><value>myname</value></property>
</bean>

View File

@@ -3,7 +3,7 @@
<beans>
<bean id="validEmptyWithDescription" class="org.springframework.beans.TestBean">
<bean id="validEmptyWithDescription" class="org.springframework.tests.sample.beans.TestBean">
<description>
I have no properties and I'm happy without them.
</description>
@@ -12,7 +12,7 @@
<!--
Check automatic creation of alias, to allow for names that are illegal as XML ids.
-->
<bean id="aliased" class=" org.springframework.beans.TestBean " name="myalias">
<bean id="aliased" class=" org.springframework.tests.sample.beans.TestBean " name="myalias">
<property name="name"><value>aliased</value></property>
</bean>
@@ -20,17 +20,17 @@
<alias name="multiAliased" alias="alias3"/>
<bean id="multiAliased" class="org.springframework.beans.TestBean" name="alias1,alias2">
<bean id="multiAliased" class="org.springframework.tests.sample.beans.TestBean" name="alias1,alias2">
<property name="name"><value>aliased</value></property>
</bean>
<alias name="multiAliased" alias="alias4"/>
<bean class="org.springframework.beans.TestBean" name="aliasWithoutId1,aliasWithoutId2,aliasWithoutId3">
<bean class="org.springframework.tests.sample.beans.TestBean" name="aliasWithoutId1,aliasWithoutId2,aliasWithoutId3">
<property name="name"><value>aliased</value></property>
</bean>
<bean class="org.springframework.beans.TestBean">
<bean class="org.springframework.tests.sample.beans.TestBean">
<property name="name"><null/></property>
</bean>
@@ -40,7 +40,7 @@
<bean class="org.springframework.beans.factory.xml.DummyReferencer"/>
<bean id="rod" class="org.springframework.beans.TestBean">
<bean id="rod" class="org.springframework.tests.sample.beans.TestBean">
<property name="name"><value><!-- a comment -->Rod</value></property>
<property name="age"><value>31</value></property>
<property name="spouse"><ref bean="father"/></property>
@@ -52,29 +52,29 @@
<!-- Should inherit age -->
</bean>
<bean id="kerry" class="org.springframework.beans.TestBean">
<bean id="kerry" class="org.springframework.tests.sample.beans.TestBean">
<property name="name"><value>Ker<!-- a comment -->ry</value></property>
<property name="age"><value>34</value></property>
<property name="spouse"><ref local="rod"/></property>
<property name="touchy"><value></value></property>
</bean>
<bean id="kathy" class="org.springframework.beans.TestBean" scope="prototype">
<bean id="kathy" class="org.springframework.tests.sample.beans.TestBean" scope="prototype">
<property name="name"><value>Kathy</value></property>
<property name="age"><value>28</value></property>
<property name="spouse"><ref bean="father"/></property>
</bean>
<bean id="typeMismatch" class="org.springframework.beans.TestBean" scope="prototype">
<bean id="typeMismatch" class="org.springframework.tests.sample.beans.TestBean" scope="prototype">
<property name="name"><value>typeMismatch</value></property>
<property name="age"><value>34x</value></property>
<property name="spouse"><ref local="rod"/></property>
</bean>
<!-- Test of lifecycle callbacks -->
<bean id="mustBeInitialized" class="org.springframework.beans.factory.MustBeInitialized"/>
<bean id="mustBeInitialized" class="org.springframework.tests.sample.beans.MustBeInitialized"/>
<bean id="lifecycle" class="org.springframework.beans.factory.LifecycleBean"
<bean id="lifecycle" class="org.springframework.tests.sample.beans.LifecycleBean"
init-method="declaredInitMethod">
<property name="initMethodDeclared"><value>true</value></property>
</bean>
@@ -85,10 +85,10 @@
</bean>
<!-- Factory beans are automatically treated differently -->
<bean id="singletonFactory" class="org.springframework.beans.factory.DummyFactory">
<bean id="singletonFactory" class="org.springframework.tests.sample.beans.factory.DummyFactory">
</bean>
<bean id="prototypeFactory" class="org.springframework.beans.factory.DummyFactory">
<bean id="prototypeFactory" class="org.springframework.tests.sample.beans.factory.DummyFactory">
<property name="singleton"><value>false</value></property>
</bean>
@@ -113,14 +113,14 @@
<property name="testBean2"><ref bean="kathy"/></property>
</bean>
<bean id="listenerVeto" class="org.springframework.beans.TestBean">
<bean id="listenerVeto" class="org.springframework.tests.sample.beans.TestBean">
<property name="name"><value>listenerVeto</value></property>
<property name="age"><value>66</value></property>
</bean>
<bean id="validEmpty" class="org.springframework.beans.TestBean"/>
<bean id="validEmpty" class="org.springframework.tests.sample.beans.TestBean"/>
<bean id="commentsInValue" class="org.springframework.beans.TestBean">
<bean id="commentsInValue" class="org.springframework.tests.sample.beans.TestBean">
<property name="name"><value>this is<!-- don't mind me --> a <![CDATA[<!--comment-->]]></value></property>
</bean>