cdi-unit / cdi-unit

Unit testing for CDI applications
http://cdi-unit.github.io/cdi-unit/
Apache License 2.0
93 stars 56 forks source link

Add support for "@Resource" injection. [CDI Extension included] #90

Closed exabrial closed 1 hour ago

exabrial commented 8 years ago

Currently cdi-unit does not support @Resource injection. Here is a simple CDI Extension that covers a huge amount of use cases:

public class AtResourceInjectionCDIExtension implements Extension {
   <T> void processAnnotatedType(@Observes ProcessAnnotatedType<T> pat) {
      Set<AnnotatedField<? super T>> fields = pat.getAnnotatedType().getFields();
      for (AnnotatedField<? super T> field : fields) {
         if (shouldInjectionAnnotationBeAddedToField(field)) {
            AnnotatedType<T> at = pat.getAnnotatedType();
            AnnotatedTypeBuilder<T> builder = new AnnotatedTypeBuilder<T>().readFromType(at);
            Inject injectAnnotation = AnnotationInstanceProvider.of(Inject.class);
            builder.addToField(field, injectAnnotation);
            pat.setAnnotatedType(builder.create());
         }
      }
   }

   private <X> boolean shouldInjectionAnnotationBeAddedToField(AnnotatedField<? super X> field) {
      return !field.isAnnotationPresent(Inject.class) && field.isAnnotationPresent(Resource.class);
   }
}
KirillGrishin commented 7 years ago

How would I use this one if it is not in the library?

seanf commented 7 years ago

@KirillGrishin I think you just need to add this to your test class:

@AdditionalClasses(AtResourceInjectionCDIExtension.class)
gitdode commented 7 years ago

Great, just what I was looking for and works fine - thanks!

KirillGrishin commented 7 years ago

@seanf Thanks, it looks to be processing it now! May I ask another question? How do I inject String resources for tests?

@Resource(name = "PROPERTIES_PATH")
private String propertiesFilePath;
exabrial commented 7 years ago

I would recommend Sabot for that: https://tomitribe.io/projects/sabot

aschoerk commented 7 years ago

Hello, at our company we faced similar problems and solved them using cdi-unit together with an additional Modul that extended the EjbExtension class and added some classes which help with transactionmanagement and queue-simulation. Perhaps you would like to take a look: ejb-cdi-unit