Skip to content

Commit

Permalink
Search potential collaborators fields in parent classes
Browse files Browse the repository at this point in the history
  • Loading branch information
vanta committed Oct 27, 2016
1 parent f7c9e8b commit 657fa72
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,28 +1,36 @@
package com.blogspot.toomuchcoding.spock.subjcollabs

import java.lang.reflect.Field

import groovy.transform.PackageScope
import org.spockframework.runtime.extension.IMethodInvocation
import spock.lang.Specification

import java.lang.reflect.Field

@PackageScope
class SubjectsCollaboratorsUtils {

public static Specification getSpec( IMethodInvocation invocation ) {
( Specification ) invocation.target.with {
public static Specification getSpec(IMethodInvocation invocation) {
(Specification) invocation.target.with {
delegate instanceof Specification ? delegate : invocation.instance
}
}

public static Collection<Field> findAllDeclaredFieldsWithAnnotation(Object object, Class... annotatedClasses) {
return object.class.declaredFields.findAll { Field field ->
annotatedClasses.any { Class annotatedClass ->
return getInheritedFields(object.class).findAll {Field field ->
annotatedClasses.any {Class annotatedClass ->
return annotatedClass in field.declaredAnnotations*.annotationType()
}
}
}

static Collection<Field> getInheritedFields(Class<?> type) {
List<Field> fields = new ArrayList<Field>()
for (Class<?> c = type; c != null; c = c.superclass) {
fields.addAll(c.declaredFields)
}
return fields
}

public static boolean isFieldSet(Field field, Object target) {
try {
boolean accessible = field.accessible
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.blogspot.toomuchcoding.spock.subjcollabs

import spock.lang.Specification


class SubjectsCollaboratorsUtilsSpec extends Specification {

def "should find collaborator fields in class with no parent"() {
given:
BaseSpec specClass = new BaseSpec()

when:
def fields = SubjectsCollaboratorsUtils.findAllDeclaredFieldsWithAnnotation(specClass, Collaborator)

then:
fields.size() == 1
fields[0].name == "field1"
}

def "should find collaborator fields in class with parent class"() {
given:
SpecClass specClass = new SpecClass()

when:
def fields = SubjectsCollaboratorsUtils.findAllDeclaredFieldsWithAnnotation(specClass, Collaborator)

then:
fields.size() == 2
fields.collect({it.getName()}).containsAll(["field1", "field3"])
}

class BaseSpec {
@Collaborator
String field1

String field2
}

class SpecClass extends BaseSpec {
@Collaborator
String field3

String field4
}

}

0 comments on commit 657fa72

Please sign in to comment.