@Override public JFieldVar apply(String nodeName, JsonNode node, JFieldVar field, Schema currentSchema) { if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations() && (node.has("minItems") || node.has("maxItems"))) { JAnnotationUse annotation = field.annotate(Size.class); if (node.has("minItems")) { annotation.param("min", node.get("minItems").asInt()); } if (node.has("maxItems")) { annotation.param("max", node.get("maxItems").asInt()); } } return field; }
private void addJsr303Annotations(final INamedParam parameter, final JVar argumentVariable) { if (isNotBlank(parameter.getPattern())) { JAnnotationUse patternAnnotation = argumentVariable.annotate(Pattern.class); patternAnnotation.param("regexp", parameter.getPattern()); } final Integer minLength = parameter.getMinLength(); final Integer maxLength = parameter.getMaxLength(); if ((minLength != null) || (maxLength != null)) { final JAnnotationUse sizeAnnotation = argumentVariable .annotate(Size.class); if (minLength != null) { sizeAnnotation.param("min", minLength); } if (maxLength != null) { sizeAnnotation.param("max", maxLength); } } final BigDecimal minimum = parameter.getMinimum(); if (minimum != null) { addMinMaxConstraint(parameter, "minimum", Min.class, minimum, argumentVariable); } final BigDecimal maximum = parameter.getMaximum(); if (maximum != null) { addMinMaxConstraint(parameter, "maximum", Max.class, maximum, argumentVariable); } if (parameter.isRequired()) { argumentVariable.annotate(NotNull.class); } }
private void addJsonTypeInfo(JDefinedClass klass, ObjectTypeDeclaration type) { if (!context.getConfig().isJacksonTypeInfo()) { return; } if (type.discriminator() == null) { return; } List<String> derivedTypes = context.getApiModel().findDerivedTypes(type.name()); if (derivedTypes.isEmpty()) { return; } JAnnotationUse typeInfo = klass.annotate(JsonTypeInfo.class); typeInfo.param("use", Id.NAME); typeInfo.param("include", As.EXISTING_PROPERTY); typeInfo.param("property", type.discriminator()); JAnnotationUse subTypes = klass.annotate(JsonSubTypes.class); JAnnotationArrayMember typeArray = subTypes.paramArray(VALUE); for (String derivedType : derivedTypes) { JDefinedClass subtype = pkg._getClass(derivedType); typeArray.annotate(Type.class).param(VALUE, subtype); } }
@Override public JFieldVar apply(String nodeName, JsonNode node, JFieldVar field, Schema currentSchema) { if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations() && (node.has("minLength") || node.has("maxLength"))) { JAnnotationUse annotation = field.annotate(Size.class); if (node.has("minLength")) { annotation.param("min", node.get("minLength").asInt()); } if (node.has("maxLength")) { annotation.param("max", node.get("maxLength").asInt()); } } return field; }
/** * Calls the correct {@link JAnnotationUse} <code>param</code> method. * * @param annot * The annotation in which the parameter will be added. * @param key * The parameter's key. * @param value * The parameter's value. */ public static void addAnnotParam(JAnnotationUse annot, String key, Object value) { if (value == null) { // Null values not accepted throw new RuntimeException("Null values not supported as annotation parameters"); } else if (value instanceof Boolean) { annot.param(key, (Boolean) value); } else if (value instanceof Integer) { annot.param(key, (Integer) value); } else if (value instanceof String) { annot.param(key, (String) value); } else if (value instanceof Class<?>) { annot.param(key, (Class<?>) value); } else if (value instanceof JType) { annot.param(key, (JType) value); } else if (value.getClass().isArray()) { Object[] valueArr = (Object[]) value; JAnnotationArrayMember aux = annot.paramArray(key); for (int i = 0; i < valueArr.length; ++i) { addAnnotArrayParam(aux, valueArr[i]); } } else { throw new RuntimeException("Impossible to construct annotation param for: " + value); } }
@SuppressWarnings("unchecked") private static JAnnotationUse getOrAddXmlSchemaAnnotation(JPackage p, JClass xmlSchemaClass) { JAnnotationUse xmlAnn = null; final List<JAnnotationUse> annotations = getAnnotations(p); if (annotations != null) { for (JAnnotationUse annotation : annotations) { final JClass clazz = getAnnotationJClass(annotation); if (clazz == xmlSchemaClass) { xmlAnn = annotation; break; } } } if (xmlAnn == null) { // XmlSchema annotation not found, let's add one xmlAnn = p.annotate(xmlSchemaClass); } return xmlAnn; }
@Test public void testClassWithPersistenceContextWithKonfiguredUnitNameSpecified() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule"); ruleField.annotate(Rule.class); final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()")); ruleField.init(instance); final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em"); final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class); jAnnotation.param("unitName", "test-unit-1"); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(cut); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class); verify(listener).testStarted(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); verify(listener).testFinished(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); }
@BeforeClass public static void generateModel() throws Exception { final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); JAnnotationUse jAnnotationUse = jClass.annotate(InitialDataSets.class); jAnnotationUse.param("value", "Script.file"); jClass.annotate(Cleanup.class); final JFieldVar jField = jClass.field(JMod.PRIVATE, String.class, "testField"); jField.annotate(PersistenceContext.class); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jAnnotationUse = jMethod.annotate(InitialDataSets.class); jAnnotationUse.param("value", "InitialDataSets.file"); jAnnotationUse = jMethod.annotate(ApplyScriptsAfter.class); jAnnotationUse.param("value", "ApplyScriptsAfter.file"); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); cut = loadClass(testFolder.getRoot(), jClass.name()); }
public Void visitAttributePropertyInfo( MAttributePropertyInfo<NType, NClass> info) { JAnnotationUse annotation = this.annotatable .annotate(XmlAttribute.class); final String name = info.getAttributeName().getLocalPart(); final String namespace = info.getAttributeName().getNamespaceURI(); annotation.param("name", name); // generate namespace property? if (!namespace.equals("")) { // assume attributeFormDefault == // unqualified annotation.param("namespace", namespace); } // TODO // if(info.isRequired()) { // xaw.required(true); // } return null; }
public void annotate(JCodeModel codeModel, JAnnotatable annotatable, XAnnotation<?> xannotation) { final JClass annotationClass = codeModel.ref(xannotation .getAnnotationClass()); JAnnotationUse annotationUse = null; for (JAnnotationUse annotation : annotatable.annotations()) { if (annotationClass.equals(annotation.getAnnotationClass())) { annotationUse = annotation; } } if (annotationUse == null) { annotationUse = annotatable.annotate(annotationClass); } final XAnnotationFieldVisitor<?> visitor = createAnnotationFieldVisitor( codeModel, annotationUse); for (XAnnotationField<?> field : xannotation.getFieldsList()) { field.accept(visitor); } }
@Override public void buildClassAnnotations(JDefinedClass jc) { // create Description annotation JAnnotationUse jad = jc.annotate(org.openhds.domain.annotations.Description.class); jad.param("description", "Standard Verbal Autopsy Questionnaire for adolescent and " + "adult deaths. (12 years and over)"); // create Entity annotation jc.annotate(javax.persistence.Entity.class); JAnnotationUse jat = jc.annotate(javax.persistence.Table.class); jat.param("name", "adultvpm"); JAnnotationUse jxmlRoot = jc.annotate(javax.xml.bind.annotation.XmlRootElement.class); jxmlRoot.param("name", "adultvpm"); }
public void buildClassAnnotations(JDefinedClass jc) { // create Description annotation JAnnotationUse jad = jc.annotate(org.openhds.domain.annotations.Description.class); jad.param("description", "All distinct Locations within the area of study are " + "represented here. A Location is identified by a uniquely generated " + "identifier that the system uses internally. Each Location has a name associated " + "with it and resides at a particular level within the Location Hierarchy."); // create Entity annotation jc.annotate(javax.persistence.Entity.class); //Persistance annotation JAnnotationUse jat = jc.annotate(javax.persistence.Table.class); jat.param("name", "location"); //XmlAnnotation jc.annotate(javax.xml.bind.annotation.XmlRootElement.class); }
public void buildClassAnnotations(JDefinedClass jc) { // create Description annotation JAnnotationUse jad = jc.annotate(org.openhds.domain.annotations.Description.class); jad.param("description", "An Individual represents one who is a part of the study. " + "Each Individual is identified by a uniquely generated external identifier which " + "the system uses internally. Information about the Individual such as name, gender, " + "date of birth, and parents are stored here. An Individual may be associated with many " + "Residencies, Relationships, and Memberships."); jc.annotate(org.openhds.domain.constraint.CheckMotherFatherNotIndividual.class); // create Entity annotation jc.annotate(javax.persistence.Entity.class); JAnnotationUse jat = jc.annotate(javax.persistence.Table.class); jat.param("name", "individual"); //XmlAnnotation JAnnotationUse jxmlRoot = jc.annotate(javax.xml.bind.annotation.XmlRootElement.class); jxmlRoot.param("name", "individual"); }
@Override public void buildClassAnnotations(JDefinedClass jc) { // create Description annotation JAnnotationUse jad = jc.annotate(org.openhds.domain.annotations.Description.class); jad.param("description", "A Vaccination is filled out for ever Pregnancy Outcome. It contains a list of " + "dates in which a child has received various immunications."); // create Entity annotation jc.annotate(javax.persistence.Entity.class); JAnnotationUse jat = jc.annotate(javax.persistence.Table.class); jat.param("name", "vaccination"); JAnnotationUse jxmlRoot = jc.annotate(javax.xml.bind.annotation.XmlRootElement.class); jxmlRoot.param("name", "vaccination"); }
@Override public void buildClassAnnotations(JDefinedClass jc) { // create Description annotation JAnnotationUse jad = jc.annotate(org.openhds.domain.annotations.Description.class); jad.param("description", "An InMigration represents a migration into the study area. " + "It contains information about the Individual who is in-migrating to a particular " + "Residency. It also contains information about the origin, date, and reason the " + "Individual is migrating as well as the Visit that is associated with the migration."); // create Entity annotation jc.annotate(javax.persistence.Entity.class); //create CheckDropdownMenuItemSelected constraint jc.annotate(org.openhds.domain.constraint.CheckDropdownMenuItemSelected.class); jc.annotate(org.openhds.domain.constraint.CheckInMigrationAfterDob.class); JAnnotationUse jat = jc.annotate(javax.persistence.Table.class); jat.param("name", "inmigration"); JAnnotationUse jxmlRoot = jc.annotate(javax.xml.bind.annotation.XmlRootElement.class); jxmlRoot.param("name", "inmigration"); }
@Override public void buildClassAnnotations(JDefinedClass jc) { // create Description annotation JAnnotationUse jad = jc.annotate(org.openhds.domain.annotations.Description.class); jad.param("description", "A Death represents the final event than an Individual can " + "have within the system. It consists of the Individual who has passed on, the " + "Visit associated with the Death, as well as descriptive information about the " + "occurrence, cause, and date of the death. If the Individual had any Residencies, " + "Relationships, or Memberships then they will become closed."); jc.annotate(org.openhds.domain.constraint.CheckDeathDateGreaterThanBirthDate.class); // create Entity annotation jc.annotate(javax.persistence.Entity.class); JAnnotationUse jat = jc.annotate(javax.persistence.Table.class); jat.param("name", "death"); JAnnotationUse jxmlRoot = jc.annotate(javax.xml.bind.annotation.XmlRootElement.class); jxmlRoot.param("name", "death"); }
@Override public void buildClassAnnotations(JDefinedClass jc) { // create Description annotation JAnnotationUse jad = jc.annotate(org.openhds.domain.annotations.Description.class); jad.param("description", "An OutMigration represents a migration out of the study area." + "It contains information about the Individual who is out-migrating to a particular" + "Residency. It also contains information about the destination, date, and reason the" + "Individual is migrating as well as the Visit associated with the migration."); // create Entity annotation jc.annotate(javax.persistence.Entity.class); JAnnotationUse jat = jc.annotate(javax.persistence.Table.class); jat.param("name", "outmigration"); JAnnotationUse jxmlRoot = jc.annotate(javax.xml.bind.annotation.XmlRootElement.class); jxmlRoot.param("name", "outmigration"); }
@Override public void buildClassAnnotations(JDefinedClass jc) { // create Description annotation JAnnotationUse jad = jc.annotate(org.openhds.domain.annotations.Description.class); jad.param("description", "A Pregnancy Observation is used to monitor a " + "pregnancy. It contains information about the mother who is pregnant, " + "the date the pregnancy started, as well as the expected delivery date."); // create Entity annotation jc.annotate(javax.persistence.Entity.class); JAnnotationUse jat = jc.annotate(javax.persistence.Table.class); jat.param("name", "pregnancyobservation"); JAnnotationUse jxmlRoot = jc.annotate(javax.xml.bind.annotation.XmlRootElement.class); jxmlRoot.param("name", "pregnancyobservation"); }
@Override public void buildClassAnnotations(JDefinedClass jc) { // create Description annotation JAnnotationUse jad = jc.annotate(org.openhds.domain.annotations.Description.class); jad.param("description", "Standard Verbal Autopsy Questionnaire PostNeonatal Deaths (28 days to <12 years)"); // create Entity annotation jc.annotate(javax.persistence.Entity.class); JAnnotationUse jat = jc.annotate(javax.persistence.Table.class); jat.param("name", "postneonatalvpm"); JAnnotationUse jxmlRoot = jc.annotate(javax.xml.bind.annotation.XmlRootElement.class); jxmlRoot.param("name", "postneonatalvpm"); }
public void buildClassAnnotations(JDefinedClass jc) { // create Description annotation JAnnotationUse jad = jc.annotate(org.openhds.domain.annotations.Description.class); jad.param("description", "A Visit represents a Field Worker's observation " + "of a specific Location within the study area at a particular date. It " + "can be identified by a uniquely generated identifier which the system " + "uses internally."); // create Entity annotation jc.annotate(javax.persistence.Entity.class); JAnnotationUse jat = jc.annotate(javax.persistence.Table.class); jat.param("name", "visit"); jc.annotate(javax.xml.bind.annotation.XmlRootElement.class); }
public void buildClassAnnotations(JDefinedClass jc) { // create Description annotation JAnnotationUse jad = jc.annotate(org.openhds.domain.annotations.Description.class); jad.param("description", "A Social Group represents a distinct family within the " + "study area. Social Groups are identified by a uniquely generated identifier " + "which the system uses internally. A Social Group has one head of house which " + "all Membership relationships are based on."); // create Entity annotation jc.annotate(javax.persistence.Entity.class); JAnnotationUse jat = jc.annotate(javax.persistence.Table.class); jat.param("name", "socialgroup"); //XmlAnnotation JAnnotationUse jxmlRoot = jc.annotate(javax.xml.bind.annotation.XmlRootElement.class); jxmlRoot.param("name", "socialgroup"); }
@Override public void buildClassAnnotations(JDefinedClass jc) { // create Description annotation JAnnotationUse jad = jc.annotate(org.openhds.domain.annotations.Description.class); jad.param("description", "Standard Verbal Autopsy Questionnaire for Neonatal Deaths (0-27 days old)"); // create Entity annotation jc.annotate(javax.persistence.Entity.class); JAnnotationUse jat = jc.annotate(javax.persistence.Table.class); jat.param("name", "neonatalvpm"); JAnnotationUse jxmlRoot = jc.annotate(javax.xml.bind.annotation.XmlRootElement.class); jxmlRoot.param("name", "neonatalvpm"); }
@Override public JFieldVar apply(String nodeName, JsonNode node, JFieldVar field, Schema currentSchema) { if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()) { JAnnotationUse annotation = field.annotate(Pattern.class); annotation.param("regexp", node.asText()); } return field; }
private void addJsonTypeInfoAnnotation(JDefinedClass jclass, JsonNode node) { if (ruleFactory.getGenerationConfig().getAnnotationStyle() == AnnotationStyle.JACKSON2) { String annotationName = node.get("deserializationClassProperty").asText(); JAnnotationUse jsonTypeInfo = jclass.annotate(JsonTypeInfo.class); jsonTypeInfo.param("use", JsonTypeInfo.Id.CLASS); jsonTypeInfo.param("include", JsonTypeInfo.As.PROPERTY); jsonTypeInfo.param("property", annotationName); } }
public static void suppressWarnings(JMethod method, String... values) { JAnnotationUse annotation = method.annotate(SuppressWarnings.class); JAnnotationArrayMember member = annotation.paramArray("value"); for( String value : values ) { member.param(value); } }
@Override public void addAnnotation(MetaAnnotation annot) { if ( this.annotations.add(annot) ) { JAnnotationUse genAnnot = getGeneratedClass().annotate(annot.getAnnotationClass()); for (String paramKey : annot.getParameters().keySet()) { Util.addAnnotParam(genAnnot, paramKey, annot.getParameters().get(paramKey)); } } }
@Override public void addAnnotation(MetaAnnotation annot) { // Add the annotation to the set of annotations if ( this.annotations.add(annot) ) { // Generate the source JAnnotationUse genAnnot = getter.annotate(annot.getAnnotationClass()); for (String paramKey : annot.getParameters().keySet()) { Util.addAnnotParam(genAnnot, paramKey, annot.getParameters().get(paramKey)); } } }
protected void addValidation(final INamedParam parameter, final JVar argumentVariable) { if (isNotBlank(parameter.getPattern())) { JAnnotationUse patternAnnotation = argumentVariable.annotate(Pattern.class); patternAnnotation.param("regexp", parameter.getPattern()); } final Integer minLength = parameter.getMinLength(); final Integer maxLength = parameter.getMaxLength(); if ((minLength != null) || (maxLength != null)) { final JAnnotationUse sizeAnnotation = argumentVariable .annotate(Size.class); if (minLength != null) { sizeAnnotation.param("min", minLength); } if (maxLength != null) { sizeAnnotation.param("max", maxLength); } } final BigDecimal minimum = parameter.getMinimum(); if (minimum != null) { addMinMaxConstraint(parameter, "minimum", Min.class, minimum, argumentVariable); } final BigDecimal maximum = parameter.getMaximum(); if (maximum != null) { addMinMaxConstraint(parameter, "maximum", Max.class, maximum, argumentVariable); } if (parameter.isRequired()) { argumentVariable.annotate(NotNull.class); } }
protected void processConfig(AnnotationGenerationInfo annotationGenerationInfo, ISimpleFacet si, PropertyCustomizerParameters cp) { JAnnotatable annotable = cp.getter; JAnnotationUse use = null; for (JAnnotationUse u : annotable.annotations()) { if (u.getAnnotationClass().fullName().equals(annotationGenerationInfo.annotationClassName)) { use = u; break; } } if (use == null) { use = annotable.annotate(writer.getModel().ref(annotationGenerationInfo.annotationClassName)); } writer.addParam(use, si.value(), annotationGenerationInfo.annotationMemberName); }
@Override public boolean run(final Outline outline, final Options options, final ErrorHandler errorHandler) { final JClass xmlNsClass = outline.getCodeModel().ref(XmlNs.class); final JClass xmlSchemaClass = outline.getCodeModel().ref(XmlSchema.class); for (PackageOutline packageOutline : outline.getAllPackageContexts()) { final JPackage p = packageOutline._package(); // get the target namespaces of all schemas that bind to the current package final Set<String> packageNamespaces = getPackageNamespace(packageOutline); // is there any prefix binding defined for the current package ? final Model packageModel = getPackageModel((PackageOutlineImpl) packageOutline); final List<Pair> list = getPrefixBinding(packageModel, packageNamespaces); acknowledgePrefixAnnotations(packageModel); if (list == null || list.isEmpty()) { // no prefix binding, nothing to do continue; } // add XML namespace prefix annotations final JAnnotationUse xmlSchemaAnnotation = getOrAddXmlSchemaAnnotation(p, xmlSchemaClass); if (xmlSchemaAnnotation == null) { throw new RuntimeException("Unable to get/add 'XmlSchema' annotation to package [" + p.name() + "]"); } final JAnnotationArrayMember members = xmlSchemaAnnotation.paramArray("xmlns"); for (Pair pair : list) { addNamespacePrefix(xmlNsClass, members, pair.getNamespace(), pair.getPrefix()); } } return true; }
private static Set<String> getPackageNamespace(PackageOutline packageOutline) { final Map<String, Integer> uriCountMap = getUriCountMap(packageOutline); final Set<String> result = new HashSet<String>(); if (uriCountMap != null) { result.addAll(uriCountMap.keySet()); } // // Find annotated methods in the ObjectFactory that create elements, and extract their namespace URIs. // final Collection<JMethod> methods = packageOutline.objectFactory().methods(); if (methods != null) { for (JMethod method : methods) { final List<JAnnotationUse> annotations = getAnnotations(method); if (annotations != null) { for (JAnnotationUse annotation : annotations) { final Map<String, JAnnotationValue> map = getAnnotationMemberValues(annotation); if (map != null) { for (Map.Entry<String, JAnnotationValue> entry : map.entrySet()) { if (entry.getKey().equals("namespace")) { final String ns = getStringAnnotationValue(entry.getValue()); result.add(ns); } } } } } } } return result; }
protected void assertSimpleAnnotation(JMethod method, String annotation, String argument) { JAnnotationUse annotationUse = method.annotations().stream() .filter(a -> a.getAnnotationClass().name().equals(annotation)).findFirst().get(); JAnnotationValue value = annotationUse.getAnnotationMembers().get("value"); StringWriter writer = new StringWriter(); JFormatter formatter = new JFormatter(writer); value.generate(formatter); assertThat(writer.toString()).isEqualTo(argument); }
protected void assertNoArgAnnotation(JMethod method, Class<?> annotation) { JAnnotationUse annotationUse = method.annotations().stream() .filter(a -> a.getAnnotationClass().name().equals(annotation.getSimpleName())).findFirst().get(); StringWriter writer = new StringWriter(); JFormatter formatter = new JFormatter(writer); annotationUse.generate(formatter); assertThat(writer.toString()).isEqualTo("@" + annotation.getName()); }
@Test public void testClassWithPersistenceUnitWithKonfiguredUnitNameSpecified() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule"); ruleField.annotate(Rule.class); final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()")); ruleField.init(instance); final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf"); final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.class); jAnnotation.param("unitName", "test-unit-1"); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(cut); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class); verify(listener).testStarted(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); verify(listener).testFinished(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); }
@Test public void testClassWithoutPersistenceContextField() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class); jAnnotationUse.param("value", JpaUnitRunner.class); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); final JpaUnitRunner runner = new JpaUnitRunner(cut); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class); verify(listener).testFailure(failureCaptor.capture()); final Failure failure = failureCaptor.getValue(); assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class)); assertThat(failure.getException().getMessage(), containsString("EntityManagerFactory or EntityManager field annotated")); }
@Test public void testClassWithMultiplePersistenceUnitFields() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class); jAnnotationUse.param("value", JpaUnitRunner.class); final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf1"); emf1Field.annotate(PersistenceUnit.class); final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf2"); emf2Field.annotate(PersistenceUnit.class); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); final JpaUnitRunner runner = new JpaUnitRunner(cut); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class); verify(listener).testFailure(failureCaptor.capture()); final Failure failure = failureCaptor.getValue(); assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class)); assertThat(failure.getException().getMessage(), containsString("Only single field is allowed")); }
@Test public void testClassWithPersistenceContextAndPersistenceUnitFields() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class); jAnnotationUse.param("value", JpaUnitRunner.class); final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em"); emf1Field.annotate(PersistenceContext.class); final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf"); emf2Field.annotate(PersistenceUnit.class); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); final JpaUnitRunner runner = new JpaUnitRunner(cut); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class); verify(listener).testFailure(failureCaptor.capture()); final Failure failure = failureCaptor.getValue(); assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class)); assertThat(failure.getException().getMessage(), containsString("either @PersistenceUnit or @PersistenceContext")); }