Class ServiceLocatorTestRule<T>
- Type Parameters:
T- the type of JUnit test thisServiceLocatorTestRuleis related to; consider making it an instance ofBinder
- All Implemented Interfaces:
Binder,org.junit.rules.TestRule
ExternalResource (and a Binder) that sets up and
tears down an HK2 ServiceLocator on a per-test-class or
per-test-method basis.- Since:
- 2.4.0-b33
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enumAnenumdescribing possibleServiceLocatorisolation levels for JUnit tests.private static final classA very, very special-purposeClassVisitorImplsuitable only for use by theServiceLocatorTestRuleclass to determine efficiently whether a givenClassis annotated withServiceor not. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate org.junit.runner.DescriptionTheDescriptiondescribing the JUnit test method currently executing.private final ServiceLocatorTestRule.ServiceLocatorIsolationTheServiceLocatorTestRule.ServiceLocatorIsolationdesignating whether theServiceLocatorassociated with thisServiceLocatorTestRuleis set up for each test method or shared among them.private ServiceLocatorTheServiceLocatorin effect for the currently executing JUnit test method.private final TThe test instance instantiating thisServiceLocatorTestRule.private final booleanAbooleanindicating whether thisServiceLocatorTestRuleis configured to output additional information toSystem.out. -
Constructor Summary
ConstructorsConstructorDescriptionServiceLocatorTestRule(T test) Creates a newServiceLocatorTestRuleon behalf of the supplied JUnit test inServiceLocatorTestRule.ServiceLocatorIsolation.PER_TESTisolation in non-verbose mode.ServiceLocatorTestRule(T test, boolean verbose) Creates a newServiceLocatorTestRuleon behalf of the supplied JUnit test inServiceLocatorTestRule.ServiceLocatorIsolation.PER_TESTisolation with the supplied verbosity.ServiceLocatorTestRule(T test, ServiceLocatorTestRule.ServiceLocatorIsolation isolation) Creates a newServiceLocatorTestRuleon behalf of the supplied JUnit test in the givenServiceLocatorTestRule.ServiceLocatorIsolationin non-verbose mode.ServiceLocatorTestRule(T test, ServiceLocatorTestRule.ServiceLocatorIsolation isolation, boolean verbose) Creates a newServiceLocatorTestRuleon behalf of the supplied JUnit test in the givenServiceLocatorTestRule.ServiceLocatorIsolation. -
Method Summary
Modifier and TypeMethodDescriptionvoidafter()Shuts down and cleans up theServiceLocatorcreated by thisServiceLocatorTestRule.org.junit.runners.model.Statementapply(org.junit.runners.model.Statement statement, org.junit.runner.Description description) Overrides theExternalResource.apply(Statement, Description)method to save the suppliedDescriptionso that other methods in this class can refer to it.voidbefore()When necessary, calls thecreateServiceLocator(Description),configureServiceLocator(ServiceLocator, Description)andperformDependencyInjection(ServiceLocator, Object)methods in order to set up aServiceLocatorappropriate for the current JUnit test.voidbind(DynamicConfiguration dynamicConfiguration) Called at the appropriate time by theconfigureServiceLocator(ServiceLocator, Description)method in case subclasses wish to add services to theServiceLocatorbeing configured.private static final voidbind(DynamicConfiguration configuration, BufferedReader reader) Reads the HK2 locator file represented by the suppliedBufferedReaderand binds theDescriptors it represents.private final voidbind(DynamicConfiguration configuration, AnnotatedElement element) Retrieves anyAnnotations found on the suppliedAnnotatedElementand calls thebind(DynamicConfiguration, Collection)method supplying them as the second parameter.private static final voidbind(DynamicConfiguration configuration, String locatorResourceName) Using the contextClassLoader, gets all classpath resources with the suppliedlocatorResourceName, and iterates through them, calling thebind(DynamicConfiguration, URL)method for each one.private static final voidbind(DynamicConfiguration configuration, URL locatorResource) Opens anInputStreamto the suppliedURL, wraps aBufferedReaderaround it, and calls thebind(DynamicConfiguration, BufferedReader)method.private final voidbind(DynamicConfiguration configuration, Collection<? extends Annotation> annotations) Recursively examines theAnnotations supplied looking for instances of theClasses,InhabitantFilesandPackagesannotations, and, using the binding methods on the suppliedDynamicConfigurationbindsDescriptors for those "reachable" classes into the configuration.private final voidbind(DynamicConfiguration configuration, Set<String> packageNames) Binds allClasses "reachable" from the supplied packages.private final voidbind(DynamicConfiguration configuration, Classes classes) private static final voidbind(DynamicConfiguration configuration, InhabitantFiles inhabitantFiles) Gathers all classpath resource names found in the suppliedInhabitantFilesannotation representing HK2 locator files and calls thebind(DynamicConfiguration, String)method for each such entry found.private final voidbind(DynamicConfiguration configuration, Packages packages) protected voidconfigureServiceLocator(ServiceLocator serviceLocator, org.junit.runner.Description testDescription) Configures the suppliedServiceLocatorfor use by the test described by the suppliedDescription.protected ServiceLocatorcreateServiceLocator(org.junit.runner.Description testDescription) Creates and returns aServiceLocatorsuitable for the JUnit test described by the suppliedDescription.getClassesFromDirectory(Set<String> packageNames, File directory, boolean verbose) Given aSetof package names and aFiledesignating an existing directory in the classpath that can be read, returns aSetofService-annotatedClasses that can be found there that belong to one of the supplied package names.getClassesFromPackages(Set<String> packageNames) getClassesFromZipFile(Set<String> packageNames, ZipFile zipFile) protected StringReturns aStringrepresenting the classpath to use to search for classes.private final org.junit.runner.DescriptionReturns theDescriptiondescribing the currently executing JUnit test method.Returns theServiceLocatorTestRule.ServiceLocatorIsolationfor thisServiceLocatorTestRule.protected StringgetServiceLocatorName(org.junit.runner.Description testDescription) Returns a name for aServiceLocatorthat is appropriate for the suppliedDescription.private static final booleanisBlacklisted(Annotation annotation) Returnstrueif the suppliedAnnotationisnullor designates an annotation type that should be excluded from recursive annotation scanning performed by thebind(DynamicConfiguration, AnnotatedElement)method.private static final booleanisBlacklisted(Class<? extends Annotation> c) Returnstrueif the suppliedClassisnullor designates an annotation type that should be excluded from recursive annotation scanning performed by thebind(DynamicConfiguration, AnnotatedElement)method.final booleanprotected voidperformDependencyInjection(ServiceLocator serviceLocator, T test) Performs HK2 dependency injection on thisServiceLocatorTestRuleand the supplied test instance, using the suppliedServiceLocatoras needed.voidshutdownAndDestroyServiceLocator(org.junit.runner.Description testDescription) Blindly calls theServiceLocator.shutdown()andServiceLocatorFactory.destroy(ServiceLocator)methods on thisServiceLocatorTestRule's associatedServiceLocatorif it is discovered to be non-null.
-
Field Details
-
test
The test instance instantiating thisServiceLocatorTestRule.This field is never
null. -
isolation
TheServiceLocatorTestRule.ServiceLocatorIsolationdesignating whether theServiceLocatorassociated with thisServiceLocatorTestRuleis set up for each test method or shared among them.This field is never
null. -
verbose
private final boolean verboseAbooleanindicating whether thisServiceLocatorTestRuleis configured to output additional information toSystem.out.- See Also:
-
description
private org.junit.runner.Description descriptionTheDescriptiondescribing the JUnit test method currently executing.This field may be
null.- See Also:
-
serviceLocator
TheServiceLocatorin effect for the currently executing JUnit test method.This field may be
null.
-
-
Constructor Details
-
ServiceLocatorTestRule
Creates a newServiceLocatorTestRuleon behalf of the supplied JUnit test inServiceLocatorTestRule.ServiceLocatorIsolation.PER_TESTisolation in non-verbose mode.- Parameters:
test- the JUnit test; must not benull- Throws:
AssertionError- iftestisnull- See Also:
-
ServiceLocatorTestRule
Creates a newServiceLocatorTestRuleon behalf of the supplied JUnit test inServiceLocatorTestRule.ServiceLocatorIsolation.PER_TESTisolation with the supplied verbosity.- Parameters:
test- the JUnit test; must not benullverbose- whether thisServiceLocatorTestRuleshould output additional information toSystem.out- Throws:
AssertionError- iftestisnull- See Also:
-
ServiceLocatorTestRule
Creates a newServiceLocatorTestRuleon behalf of the supplied JUnit test in the givenServiceLocatorTestRule.ServiceLocatorIsolationin non-verbose mode.- Parameters:
test- the JUnit test; must not benullisolation- theServiceLocatorTestRule.ServiceLocatorIsolation; ifnullthenServiceLocatorTestRule.ServiceLocatorIsolation.PER_TESTwill be used instead- Throws:
AssertionError- iftestisnull- See Also:
-
ServiceLocatorTestRule
public ServiceLocatorTestRule(T test, ServiceLocatorTestRule.ServiceLocatorIsolation isolation, boolean verbose) Creates a newServiceLocatorTestRuleon behalf of the supplied JUnit test in the givenServiceLocatorTestRule.ServiceLocatorIsolation.- Parameters:
test- the JUnit test; must not benullisolation- theServiceLocatorTestRule.ServiceLocatorIsolation; ifnullthenServiceLocatorTestRule.ServiceLocatorIsolation.PER_TESTwill be used insteadverbose- whether thisServiceLocatorTestRuleshould output additional information toSystem.out- Throws:
AssertionError- iftestisnull
-
-
Method Details
-
getServiceLocatorIsolation
Returns theServiceLocatorTestRule.ServiceLocatorIsolationfor thisServiceLocatorTestRule.This method never returns
null.- Returns:
- the
ServiceLocatorTestRule.ServiceLocatorIsolationfor thisServiceLocatorTestRule; nevernull
-
getDescription
private final org.junit.runner.Description getDescription()Returns theDescriptiondescribing the currently executing JUnit test method.This method may return
null.- Returns:
- the
Descriptiondescribing the currently executing JUnit test method, ornull
-
isVerbose
public final boolean isVerbose()- Returns:
trueif thisServiceLocatorTestRuleshould be verbose;falseotherwise- See Also:
-
before
When necessary, calls thecreateServiceLocator(Description),configureServiceLocator(ServiceLocator, Description)andperformDependencyInjection(ServiceLocator, Object)methods in order to set up aServiceLocatorappropriate for the current JUnit test.- Overrides:
beforein classorg.junit.rules.ExternalResource- Throws:
IOException- if theconfigureServiceLocator(ServiceLocator, Description)method threw anIOException- See Also:
-
configureServiceLocator
protected void configureServiceLocator(ServiceLocator serviceLocator, org.junit.runner.Description testDescription) throws IOException Configures the suppliedServiceLocatorfor use by the test described by the suppliedDescription.This implementation:
- Adds the
ErrorServiceImplclass to the suppliedServiceLocatorso that exceptions will be thrown from tests - Removes, via
DynamicConfiguration.addUnbindFilter(Filter), allDescriptors that haveDescription.classas one of their contracts - Adds a constant
descriptor in
Singletonscope with a name equal to the return value of theDescription.getDisplayName()method for the suppliedDescriptionso that the current test can inject theDescriptionfor the current method if it wishes - Adds any classes found in an optional
Classesannotation decorating the test class—if they are assignable toFactory.classthen they are added as factories - Adds any classes found in any packages listed in an optional
Packagesannotation decorating the test class, provided they are annotated withService - Reads any locator files listed in an optional
InhabitantFilesannotation decorating the test class and adds the services listed therein - Calls the
bind(DynamicConfiguration)method - Calls the
Binder.bind(DynamicConfiguration)method on the test if it is in fact an instance ofBinder
- Parameters:
serviceLocator- theServiceLocatorto configure; must not benulltestDescription- theDescriptiondescribing the particular test being run; must not benull- Throws:
AssertionError- if eitherserviceLocatorortestDescriptionisnullIOException- if there was an error looking for classes in packages or finding or reading locator files
- Adds the
-
bind
Called at the appropriate time by theconfigureServiceLocator(ServiceLocator, Description)method in case subclasses wish to add services to theServiceLocatorbeing configured.Overrides of this method must not invoke the
DynamicConfiguration.commit()method.The default implementation of this method does nothing.
- Specified by:
bindin interfaceBinder- Parameters:
dynamicConfiguration- theDynamicConfigurationto manipulate in order to add or remove services from theServiceLocatorbeing configured; must not benull
-
getClassesFromPackages
Given aSetof package names, returns aSetofService-annotatedClasses found in those packages, whether they are located inZipFiles or directories on the classpath.This method never returns
null.- Parameters:
packageNames- the names of packages to search; may benullin which case an emptySetwill be returned- Returns:
- a non-
nullSetofClasses - Throws:
IOException- if there was any kind of error during package searching or file reading- See Also:
-
getClassesFromZipFile
private final Set<Class<?>> getClassesFromZipFile(Set<String> packageNames, ZipFile zipFile) throws IOException Given aZipFile(which is usually a.jarfile) containing class files and aSetof package names, searches it to findService-annotatedClasses inside it that belong to one of the supplied package names and returns aSetof suchClasses.- Parameters:
packageNames- aSetof package names; may benullin which case an emptySetwill be returnedzipFile- aZipFilehopefully containing class files; may benullin which case an emptySetwill be returned- Returns:
- a non-
nullSetofService-annotatedClasses - Throws:
IOException- if an error occurred reading theZipFile
-
getClasspath
Returns aStringrepresenting the classpath to use to search for classes.This method never returns
null.Overrides of this method are permitted to return
null.The default implementation of this method returns the value of the
java.class.pathsystem property, or in the almost certainly catastrophic case where this is not set, the empty string.- Returns:
- a
Stringrepresenting the classpath, ornull
-
bind
private final void bind(DynamicConfiguration configuration, AnnotatedElement element) throws IOException Retrieves anyAnnotations found on the suppliedAnnotatedElementand calls thebind(DynamicConfiguration, Collection)method supplying them as the second parameter.- Parameters:
configuration- aDynamicConfigurationthat will perform the binding; must not benullelement- theAnnotatedElementthat has annotations; may benullin which case no action is performed- Throws:
AssertionError- ifconfigurationisnullIOException- if there was a problem reading class or locator files- See Also:
-
bind
private final void bind(DynamicConfiguration configuration, Collection<? extends Annotation> annotations) throws IOException Recursively examines theAnnotations supplied looking for instances of theClasses,InhabitantFilesandPackagesannotations, and, using the binding methods on the suppliedDynamicConfigurationbindsDescriptors for those "reachable" classes into the configuration.Recursively means that a user-defined
Annotationmight itself be annotated withClasses; in such a case theClassesannotation's contents will be found and processed. This effectively allows stereotyping theClasses,InhabitantFilesandPackagesannotations.- Parameters:
configuration- aDynamicConfigurationthat will perform the binding; must not benullannotations- aCollectionofAnnotations; may benullin which case no action will be performed- Throws:
AssertionError- ifconfigurationisnullIOException- if there was a problem reading class or locator files- See Also:
-
bind
Binds allClasses "reachable" from the suppliedClassesannotation.Each
Classfound as a member of the return value of theClasses.value()method is bound (even if it is an implementation ofFactory) and in turn is examined forAnnotations on itself.- Parameters:
configuration- aDynamicConfigurationthat will perform the binding; must not benullclasses- aClasses; may benullin which case no action will be performed- Throws:
AssertionError- ifconfigurationisnullIOException- if there was a problem reading class files or locator files- See Also:
-
bind
Binds allClasses "reachable" from packages described by the suppliedPackagesannotation.This method calls the
bind(DynamicConfiguration, Set)method, passing it aSetformed from the suppliedPackagesannotation's list of package names as the second parameter.- Parameters:
configuration- aDynamicConfigurationthat will perform the binding; must not benullpackages- aPackages; may benullin which case no action will be performed- Throws:
AssertionError- ifconfigurationisnullIOException- if there was a problem reading class files or locator files- See Also:
-
bind
private final void bind(DynamicConfiguration configuration, Set<String> packageNames) throws IOException Binds allClasses "reachable" from the supplied packages.This method calls the
getClassesFromPackages(Set)method, and, for eachClassreturned, if it is an implementation ofFactorythen twoDescriptors are added to theDynamicConfigurationin the form of aFactoryDescriptorsaddition by way of theDynamicConfiguration.addActiveFactoryDescriptor(Class)method, or, if not, then a singleDescriptoris added to theDynamicConfiguration.- Parameters:
configuration- aDynamicConfigurationthat will perform the binding; must not benullpackageNames- aSetof package names; may benullin which case no action will be performed- Throws:
AssertionError- ifconfigurationisnullIOException- if there was a problem reading class files or locator files- See Also:
-
performDependencyInjection
Performs HK2 dependency injection on thisServiceLocatorTestRuleand the supplied test instance, using the suppliedServiceLocatoras needed.The default implementation of this method does the following:
- Calls
ServiceLocator.inject(Object)on the suppliedServiceLocator, if it is non-null, passing it thisServiceLocatorTestRule - Calls
ServiceLocator.postConstruct(Object)on the suppliedServiceLocator, if it is non-null, passing it thisServiceLocatorTestRule - Calls
ServiceLocator.inject(Object)on the suppliedServiceLocator, if it is non-null, passing it the suppliedtestinstance, if it is non-null - Calls
ServiceLocator.postConstruct(Object)on the suppliedServiceLocator, if it is non-null, passing it the suppliedtestinstance, if it is non-null
This method is guaranteed to be called after the
configureServiceLocator(ServiceLocator, Description)method with the sameServiceLocator.- Parameters:
serviceLocator- theServiceLocatorto use to perform injection; may benullin which case no action will be takentest- the test instance to inject; may benull- See Also:
- Calls
-
createServiceLocator
Creates and returns aServiceLocatorsuitable for the JUnit test described by the suppliedDescription.This method never returns
null.Overrides of this method must not return
null.- Parameters:
testDescription- theDescriptiondescribing the currently executing JUnit test; must not benull- Returns:
- a non-
nullServiceLocator - Throws:
AssertionError- iftestDescriptionisnull
-
getServiceLocatorName
Returns a name for aServiceLocatorthat is appropriate for the suppliedDescription.This method never returns
null.Overrides of this method must not return
null.- Parameters:
testDescription- theDescriptiondescribing the currently executing JUnit test; must not benull- Returns:
- a non-
nullStringthat will be used as a name for aServiceLocator - Throws:
AssertionError- iftestDescriptionisnull, or if itsgetClassName()method returnsnullor if itsgetMethodName()method returnsnull
-
apply
public org.junit.runners.model.Statement apply(org.junit.runners.model.Statement statement, org.junit.runner.Description description) Overrides theExternalResource.apply(Statement, Description)method to save the suppliedDescriptionso that other methods in this class can refer to it.This method never returns
null.Overrides of this method must not return
null.- Specified by:
applyin interfaceorg.junit.rules.TestRule- Overrides:
applyin classorg.junit.rules.ExternalResource- Parameters:
statement- theStatementthisServiceLocatorTestRulewill modify; passed unchanged to theExternalResource.apply(Statement, Description)methoddescription- theDescriptiondescribing the current JUnit test; must not benull; passed unchanged to theExternalResource.apply(Statement, Description)method- Returns:
- the return value of the
ExternalResource.apply(Statement, Description)method; nevernull
-
after
public void after()Shuts down and cleans up theServiceLocatorcreated by thisServiceLocatorTestRule.This method performs the following actions in order:
- Calls the
ServiceLocator.preDestroy(Object)method on the existingServiceLocator, passing it the test instance supplied at construction time - Calls the
ServiceLocator.preDestroy(Object)method on the existingServiceLocator, passing it thisServiceLocatorTestRule - If the
ServiceLocatorisolation level isPER_TEST, calls theshutdownAndDestroyServiceLocator(Description)method with aDescriptioninstance that describes the JUnit test method that just executed
- Overrides:
afterin classorg.junit.rules.ExternalResource- See Also:
- Calls the
-
shutdownAndDestroyServiceLocator
public void shutdownAndDestroyServiceLocator(org.junit.runner.Description testDescription) Blindly calls theServiceLocator.shutdown()andServiceLocatorFactory.destroy(ServiceLocator)methods on thisServiceLocatorTestRule's associatedServiceLocatorif it is discovered to be non-null.- Parameters:
testDescription- aDescriptiondescribing the currently executing JUnit test, if any; ignored by this method's default implementation; may benull
-
getClassesFromDirectory
private static final Set<Class<?>> getClassesFromDirectory(Set<String> packageNames, File directory, boolean verbose) throws IOException Given aSetof package names and aFiledesignating an existing directory in the classpath that can be read, returns aSetofService-annotatedClasses that can be found there that belong to one of the supplied package names.This method never returns
null.- Parameters:
packageNames- aSetof package names; may benullin which case an emptySetwill be returneddirectory- aFiledesignating a directory; an emptySetwill be returned unless the directory so designated exists and is readableverbose- whether additional information should be output- Returns:
- a non-
nullSetofService-annotatedClasses - Throws:
IOException- if there was a problem reading files
-
isBlacklisted
Returnstrueif the suppliedAnnotationisnullor designates an annotation type that should be excluded from recursive annotation scanning performed by thebind(DynamicConfiguration, AnnotatedElement)method.- Parameters:
annotation- theAnnotationto consider; may benullin which casetruewill be returned- Returns:
trueif the suppliedAnnotationisnullor designates an annotation type that should be excluded from recursive annotation scanning performed by thebind(DynamicConfiguration, AnnotatedElement)method- See Also:
-
isBlacklisted
Returnstrueif the suppliedClassisnullor designates an annotation type that should be excluded from recursive annotation scanning performed by thebind(DynamicConfiguration, AnnotatedElement)method.- Parameters:
c- theClassto consider; may benullin which casetruewill be returned- Returns:
trueif the suppliedClassisnullor designates an annotation type that should be excluded from recursive annotation scanning performed by thebind(DynamicConfiguration, AnnotatedElement)method;falseotherwise
-
bind
private static final void bind(DynamicConfiguration configuration, InhabitantFiles inhabitantFiles) throws IOException Gathers all classpath resource names found in the suppliedInhabitantFilesannotation representing HK2 locator files and calls thebind(DynamicConfiguration, String)method for each such entry found.- Parameters:
configuration- aDynamicConfigurationthat will perform the binding; must not benullinhabitantFiles- anInhabitantFiles; may benullin which case no action will be performed- Throws:
AssertionError- ifconfigurationisnullIOException- if there was a problem reading locator files- See Also:
-
bind
private static final void bind(DynamicConfiguration configuration, String locatorResourceName) throws IOException Using the contextClassLoader, gets all classpath resources with the suppliedlocatorResourceName, and iterates through them, calling thebind(DynamicConfiguration, URL)method for each one.- Parameters:
configuration- aDynamicConfigurationthat will perform the binding; must not benulllocatorResourceName- the name of a classpath resource identifying one or more HK2 locator files; may benullin which case no action will be performed- Throws:
AssertionError- ifconfigurationisnullIOException- if there was a problem reading locator files- See Also:
-
bind
private static final void bind(DynamicConfiguration configuration, URL locatorResource) throws IOException Opens anInputStreamto the suppliedURL, wraps aBufferedReaderaround it, and calls thebind(DynamicConfiguration, BufferedReader)method.- Parameters:
configuration- aDynamicConfigurationthat will perform the binding; must not benulllocatorResource- aURLto an HK2 locator resource; may benullin which case no action will be taken- Throws:
AssertionError- ifconfigurationisnullIOException- if there was a problem reading locator files- See Also:
-
bind
private static final void bind(DynamicConfiguration configuration, BufferedReader reader) throws IOException Reads the HK2 locator file represented by the suppliedBufferedReaderand binds theDescriptors it represents.- Parameters:
configuration- aDynamicConfigurationthat will perform the binding; must not benullreader- aBufferedReaderreading a stream of descriptor information as parseable by theDescriptorImpl.readObject(BufferedReader)method; may benullin which case no action will be performed- Throws:
AssertionError- ifconfigurationisnullIOException- if there was a problem reading locator files- See Also:
-