src/test/java/ru/indvdum/jpa/tests/AbstractJPAEntityTest.groovy
changeset 2 f692598b3742
child 10 7241826f43f6
equal deleted inserted replaced
1:452e65d696a3 2:f692598b3742
       
     1 package ru.indvdum.jpa.tests
       
     2 ;
       
     3 
       
     4 import static org.junit.Assert.*
       
     5 
       
     6 import java.lang.reflect.Field
       
     7 import java.lang.reflect.Method
       
     8 import java.lang.reflect.Modifier
       
     9 
       
    10 import javax.persistence.EmbeddedId
       
    11 import javax.persistence.Entity
       
    12 import javax.persistence.GeneratedValue
       
    13 import javax.persistence.Id
       
    14 import javax.persistence.IdClass
       
    15 import javax.persistence.Transient
       
    16 
       
    17 import org.junit.Test
       
    18 
       
    19 import ru.indvdum.jpa.dao.JPADataAccessObject
       
    20 import ru.indvdum.jpa.entities.AbstractEntity;
       
    21 
       
    22 
       
    23 /**
       
    24  * JUnit test case for testing of a creating, listing, updating and removing 
       
    25  * operations with database of the JPA entities.
       
    26  * 
       
    27  * @author 	indvdum (gotoindvdum@gmail.com)
       
    28  * @since 23.12.2011 22:54:26
       
    29  *
       
    30  */
       
    31 abstract class AbstractJPAEntityTest extends AbstractJPATest {
       
    32 
       
    33 	protected def uniqueValue = 1
       
    34 	protected JPADataAccessObject dao = null
       
    35 	protected Set toRemove = new HashSet()
       
    36 
       
    37 	@Test
       
    38 	public void testEntity() {
       
    39 		dao = createDAO()
       
    40 		try {
       
    41 			testEntity(getEntityClass())
       
    42 		} finally {
       
    43 			dao.close()		
       
    44 		}
       
    45 	}
       
    46 	
       
    47 	/**
       
    48 	 * @return Your implementation of JPADataAccessObject
       
    49 	 */
       
    50 	protected abstract JPADataAccessObject createDAO();
       
    51 
       
    52 	/**
       
    53 	 * Test creating, listing, updating, and removing of an {@code entityClass} object
       
    54 	 * 
       
    55 	 * @param entityClass
       
    56 	 */
       
    57 	protected void testEntity(Class entityClass) {
       
    58 		
       
    59 		assert AbstractEntity.class.isAssignableFrom(entityClass)
       
    60 
       
    61 		Map<String, Object> fieldsValues
       
    62 		def dbEntity
       
    63 
       
    64 		// creating
       
    65 		def entity = createEntity(entityClass)
       
    66 		testCreatedEntity(entity)
       
    67 
       
    68 		// listing
       
    69 		toRemove.each {
       
    70 			assert dao.list(it.class).each { it2 ->
       
    71 				assert it.class.isAssignableFrom(it2.class)
       
    72 			}.size() == toRemove.findAll { it2 ->
       
    73 				it.class.isAssignableFrom(it2.class)
       
    74 			}.size()
       
    75 		}
       
    76 
       
    77 		// updating
       
    78 		fieldsValues = updateFields(entity)
       
    79 		assert dao.persist(entity)
       
    80 		assert dao.contains(entity)
       
    81 		dbEntity = dao.find(entityClass, (entity as AbstractEntity).getIdentifierValue())
       
    82 		assert dbEntity != null
       
    83 		assert checkEntityFieldValues(dbEntity, fieldsValues)
       
    84 		testUpdatedEntity(entity)
       
    85 
       
    86 		// removing
       
    87 		assert dao.remove(toRemove)
       
    88 		assert !dao.contains(toRemove)
       
    89 		testRemovedEntity(entity)
       
    90 	}
       
    91 	
       
    92 	/**
       
    93 	 * Create and persist to database an {@code entityClass} object
       
    94 	 * 
       
    95 	 * @param entityClass
       
    96 	 * @return created entity object
       
    97 	 */
       
    98 	protected Object createEntity(Class entityClass) {
       
    99 		assertNotNull entityClass.annotations.find {it instanceof Entity}
       
   100 		def entity = entityClass.newInstance()
       
   101 		assert entity.class == entityClass
       
   102 		toRemove.add(entity)
       
   103 		
       
   104 		Map<String, Object> fieldsValues = updateFields(entity)
       
   105 		assert dao.persist(entity)
       
   106 		assert dao.contains(entity)
       
   107 		def dbEntity = dao.find(entityClass, (entity as AbstractEntity).getIdentifierValue())
       
   108 		assert dbEntity != null
       
   109 		assert checkEntityFieldValues(dbEntity, fieldsValues)
       
   110 		
       
   111 		return entity
       
   112 	}
       
   113 
       
   114 	/**
       
   115 	 * Update all fields of an {@code entity} object
       
   116 	 * @param entity
       
   117 	 * @return generated field values
       
   118 	 */
       
   119 	protected Map<String, Object> updateFields(Object entity) {
       
   120 		Map<String, Object> fieldsValues = new HashMap<String, Object>()
       
   121 		getFields(entity).grep {
       
   122 			it.annotations.find {
       
   123 				it instanceof Transient || it instanceof GeneratedValue
       
   124 			} == null
       
   125 		}.each {
       
   126 			def newValue = generateFieldValue(entity, it)
       
   127 			setFieldValueBySetter(entity, it, newValue)
       
   128 			fieldsValues.put(it.name, newValue)
       
   129 		}
       
   130 		return fieldsValues
       
   131 	}
       
   132 	
       
   133 	/**
       
   134 	 * Collections and arrays will not be processed
       
   135 	 * 
       
   136 	 * @param entity
       
   137 	 * @param field
       
   138 	 * @return generated field value
       
   139 	 */
       
   140 	protected Object generateFieldValue(Object entity, Field field) {
       
   141 		def type = field.getType()
       
   142 		def newValue
       
   143 		if(type.toString() == 'boolean' || type == Boolean.class) {
       
   144 			newValue = (boolean) (uniqueValue++ % 2i == 0i)
       
   145 		} else if(type.toString() == 'byte' || type == Byte) {
       
   146 			newValue = (byte) (uniqueValue++ % Byte.MAX_VALUE + 1i)
       
   147 		} else if(type.toString() == 'char' || type == Character) {
       
   148 			newValue = (char) (uniqueValue++ % (int) Character.MAX_VALUE + 1i)
       
   149 		} else if(type.toString() == 'short' || type == Short) {
       
   150 			newValue = (short) (uniqueValue++ % Short.MAX_VALUE + 1i)
       
   151 		} else if(type.toString() == 'int' || type == Integer) {
       
   152 			newValue = (int) (uniqueValue++ % Integer.MAX_VALUE + 1i)
       
   153 		} else if(type.toString() == 'long' || type == Long) {
       
   154 			newValue = (long) uniqueValue++ % Long.MAX_VALUE + 1L
       
   155 		} else if(type.toString() == 'float' || type == Float) {
       
   156 			newValue = (float) uniqueValue++ % Float.MAX_VALUE + 1f
       
   157 		} else if(type.toString() == 'double' || type == Double) {
       
   158 			newValue = (double) uniqueValue++ % Double.MAX_VALUE + 1d
       
   159 		} else if(type == String.class) {
       
   160 			newValue = (String) "test${uniqueValue++}"
       
   161 		} else if(type instanceof Class && (type as Class).annotations.find {it instanceof Entity} != null) { // modifying of a primary keys is deprecated
       
   162 			// an attempt to use already created entities
       
   163 			def currentValue = getFieldValue(entity, field)
       
   164 			newValue = toRemove.find {it.class == type && it != currentValue}
       
   165 			if(newValue == null)
       
   166 				newValue = createEntity(type as Class)
       
   167 		} else if(
       
   168 				type instanceof Class 
       
   169 				&& !(
       
   170 					field.clazz.annotations.find {it instanceof IdClass} != null 
       
   171 					&& field.declaredAnnotations.find {it instanceof Id} != null
       
   172 				)
       
   173 				&& field.declaredAnnotations.find {it instanceof EmbeddedId} == null
       
   174 				&& !Collection.class.isAssignableFrom(type)
       
   175 				&& !(type as Class).isArray()
       
   176 			) { // modifying of a primary keys is deprecated
       
   177 			newValue = (type as Class).newInstance()
       
   178 		} else {
       
   179 			newValue = getFieldValue(entity, field)
       
   180 		}
       
   181 		return newValue
       
   182 	}
       
   183 
       
   184 	/**
       
   185 	 * @param entity
       
   186 	 * @param rightValues
       
   187 	 * @return {@code true}, if all entity fields is equals to {@code rightValues}
       
   188 	 */
       
   189 	protected boolean checkEntityFieldValues(Object entity, Map<String, Object> rightValues) {
       
   190 		def result = true
       
   191 		def fields = getFields(entity)
       
   192 		rightValues.each {  key, value ->
       
   193 			fields.find { it.name == key }.each {
       
   194 				if(!getFieldValue(entity, it).equals(value)) {
       
   195 					result = false
       
   196 				}
       
   197 			}
       
   198 		}
       
   199 		return result
       
   200 	}
       
   201 
       
   202 	/**
       
   203 	 * Set a {@code field} to a {@code value} of an entity {@code object}
       
   204 	 * 
       
   205 	 * @param object
       
   206 	 * @param field
       
   207 	 * @param value
       
   208 	 */
       
   209 	protected void setFieldValue(Object object, Field field, Object value) {
       
   210 		boolean isAccessible = field.accessible
       
   211 		field.accessible = true
       
   212 		field.set(object, value)
       
   213 		field.accessible = isAccessible
       
   214 	}
       
   215 	
       
   216 	/**
       
   217 	 * Trying set a {@code field} to a {@code value} of an entity {@code object}
       
   218 	 * by using a setter method. If setter not found, field will be set directly
       
   219 	 * throw {@code setFieldValue} method.
       
   220 	 * 
       
   221 	 * @param object
       
   222 	 * @param field
       
   223 	 * @param value
       
   224 	 */
       
   225 	protected void setFieldValueBySetter(Object object, Field field, Object value) {
       
   226 		boolean isSetted = false
       
   227 		getMethods(object).grep {
       
   228 			(
       
   229 				Modifier.isPublic(it.modifiers) 
       
   230 				&& it.parameterTypes.size() == 1 
       
   231 				&& (
       
   232 					value == null 
       
   233 					|| it.parameterTypes[0].isAssignableFrom(value.class)
       
   234 					)
       
   235 				&& it.name =~ /^set(?i:${field.name.charAt(0)})${field.name.replaceFirst("^.{1}", "")}/
       
   236 			)
       
   237 		}.each {
       
   238 			object."${it.name}"(value)
       
   239 			isSetted = true
       
   240 		}
       
   241 		if(isSetted)
       
   242 			return
       
   243 		setFieldValue(object, field, value)
       
   244 	}
       
   245 
       
   246 	/**
       
   247 	 * @param object
       
   248 	 * @param field
       
   249 	 * @return the field value of an object
       
   250 	 */
       
   251 	protected Object getFieldValue(Object object, Field field) {
       
   252 		boolean isAccessible = field.accessible
       
   253 		field.accessible = true
       
   254 		def value = field.get(object)
       
   255 		field.accessible = isAccessible
       
   256 		return value
       
   257 	}
       
   258 
       
   259 	/**
       
   260 	 * @param obj
       
   261 	 * @return all object fields, including inherited
       
   262 	 */
       
   263 	protected Collection<Field> getFields(obj) {
       
   264 		Class clazz = obj.getClass()
       
   265 		Collection<Field> fields = clazz.declaredFields
       
   266 		while(clazz.superclass != null) {
       
   267 			clazz = clazz.superclass
       
   268 			fields.addAll(clazz.declaredFields)
       
   269 		}
       
   270 		fields.grep {
       
   271 			!it.synthetic &&
       
   272 					!Modifier.isStatic(it.modifiers) &&
       
   273 					!Modifier.isTransient(it.modifiers)
       
   274 		}
       
   275 	}
       
   276 
       
   277 	/**
       
   278 	 * @param obj
       
   279 	 * @return all object methods, including inherited
       
   280 	 */
       
   281 	protected Collection<Method> getMethods(obj) {
       
   282 		Class clazz = obj.getClass()
       
   283 		Collection<Method> methods = clazz.declaredMethods
       
   284 		while(clazz.superclass != null) {
       
   285 			clazz = clazz.superclass
       
   286 			methods.addAll(clazz.declaredMethods)
       
   287 		}
       
   288 		methods.grep {
       
   289 			!it.synthetic &&
       
   290 					!Modifier.isStatic(it.modifiers) &&
       
   291 					!Modifier.isTransient(it.modifiers)
       
   292 		}
       
   293 	}
       
   294 	
       
   295 	/**
       
   296 	 * For implement in successors
       
   297 	 *
       
   298 	 * @param entity
       
   299 	 */
       
   300 	protected void testCreatedEntity(Object entity) {
       
   301 		
       
   302 	}
       
   303 	
       
   304 	/**
       
   305 	 * For implement in successors
       
   306 	 *
       
   307 	 * @param entity
       
   308 	 */
       
   309 	protected void testUpdatedEntity(Object entity) {
       
   310 		
       
   311 	}
       
   312 	
       
   313 	/**
       
   314 	 * For implement in successors
       
   315 	 *
       
   316 	 * @param entity
       
   317 	 */
       
   318 	protected void testRemovedEntity(Object entity) {
       
   319 		
       
   320 	}
       
   321 
       
   322 	/**
       
   323 	 * @return an {@link AbstractEntity} successor
       
   324 	 */
       
   325 	abstract protected Class getEntityClass()
       
   326 }