@Override public org.jsonschema2pojo.rules.Rule<JPackage, JType> getObjectRule() { final org.jsonschema2pojo.rules.Rule<JPackage, JType> workingRule = super.getObjectRule(); return new org.jsonschema2pojo.rules.Rule<JPackage, JType>() { @Override public JType apply(String nodeName, JsonNode node, JPackage generatableType, Schema currentSchema) { JType objectType = workingRule.apply(nodeName, node, generatableType, currentSchema); if( objectType instanceof JDefinedClass ) { JDefinedClass jclass = (JDefinedClass)objectType; jclass.method(JMod.PUBLIC, jclass.owner().BOOLEAN, "brokenMethod").body(); } return objectType; } }; }
@Test public void class_has_source_of_import() throws Exception { ArchConfiguration.get().setMd5InClassSourcesEnabled(true); JavaClass clazzFromFile = new ClassFileImporter().importClass(ClassToImportOne.class); Source source = clazzFromFile.getSource().get(); assertThat(source.getUri()).isEqualTo(urlOf(ClassToImportOne.class).toURI()); assertThat(source.getMd5sum()).isEqualTo(md5sumOf(bytesAt(urlOf(ClassToImportOne.class)))); JavaClass clazzFromJar = new ClassFileImporter().importClass(Rule.class); source = clazzFromJar.getSource().get(); assertThat(source.getUri()).isEqualTo(urlOf(Rule.class).toURI()); assertThat(source.getMd5sum()).isEqualTo(md5sumOf(bytesAt(urlOf(Rule.class)))); ArchConfiguration.get().setMd5InClassSourcesEnabled(false); source = new ClassFileImporter().importClass(ClassToImportOne.class).getSource().get(); assertThat(source.getMd5sum()).isEqualTo(MD5_SUM_DISABLED); }
@Test public void matches_annotation_by_type() { assertThat(annotatedWith(RuntimeRetentionAnnotation.class).apply(importClassWithContext(AnnotatedClass.class))) .as("annotated class matches").isTrue(); assertThat(annotatedWith(RuntimeRetentionAnnotation.class.getName()).apply(importClassWithContext(AnnotatedClass.class))) .as("annotated class matches").isTrue(); assertThat(annotatedWith(RuntimeRetentionAnnotation.class).apply(importClassWithContext(Object.class))) .as("annotated class matches").isFalse(); assertThat(annotatedWith(RuntimeRetentionAnnotation.class.getName()).apply(importClassWithContext(Object.class))) .as("annotated class matches").isFalse(); assertThat(annotatedWith(Rule.class).getDescription()) .isEqualTo("annotated with @Rule"); assertThat(annotatedWith(Rule.class.getName()).getDescription()) .isEqualTo("annotated with @Rule"); }
/** * Throw an {@link IllegalStateException} if the supplied {@code testClass} * does not declare a {@code public SpringMethodRule} field that is * annotated with {@code @Rule}. */ private static void validateSpringMethodRuleConfiguration(Class<?> testClass) { Field ruleField = null; for (Field field : testClass.getFields()) { int modifiers = field.getModifiers(); if (!Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers) && SpringMethodRule.class.isAssignableFrom(field.getType())) { ruleField = field; break; } } if (ruleField == null) { throw new IllegalStateException(String.format( "Failed to find 'public SpringMethodRule' field in test class [%s]. " + "Consult the javadoc for SpringClassRule for details.", testClass.getName())); } if (!ruleField.isAnnotationPresent(Rule.class)) { throw new IllegalStateException(String.format( "SpringMethodRule field [%s] must be annotated with JUnit's @Rule annotation. " + "Consult the javadoc for SpringClassRule for details.", ruleField)); } }
@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")); }
private void initClassFields(Object target, Class<?> targetClass) { Field[] targetFields = targetClass.getDeclaredFields(); for (Field field : targetFields) { if (field.getAnnotation(Rule.class) == null) { if (!Modifier.isStatic(field.getModifiers())) { field.setAccessible(true); try { final Object value = field.get(target); if (value != null) { fields.put(new ObjectId(field), new Provider() { @Override public Object get() { return value; } }); } } catch (IllegalAccessException e) { throw new RuntimeException("Error accessing field " + field, e); } } } } }
@Rule public final TestRule openAndCloseDriver() { return (base, description) -> new Statement() { @Override public void evaluate() throws Throwable { driver = createDriver(); try { base.evaluate(); } finally { if (closeDriver) try { driver.close(); } catch (Throwable t) { // swallow } } } }; }
@Override public void visitEnd() { if (transformationParameters.isJUnit4RuleInjectionRequired) { FieldVisitor fv = super.visitField(Opcodes.ACC_PUBLIC, "scottReportingRule", Type.getDescriptor(ScottReportingRule.class), null, null); fv.visitAnnotation(Type.getDescriptor(Rule.class), true).visitEnd(); } if (transformationParameters.isJUnit5ExtensionInjectionRequired) { AnnotationVisitor av0 = super.visitAnnotation("Lorg/junit/jupiter/api/extension/ExtendWith;", true); AnnotationVisitor av1 = av0.visitArray("value"); av1.visit(null, Type.getType("Lhu/advancedweb/scott/runtime/ScottJUnit5Extension;")); av1.visitEnd(); av0.visitEnd(); } super.visitEnd(); }
/** * @return {@code true} if the test class has any fields annotated with {@code Rule} whose type * is {@link Timeout}. */ static boolean hasTimeoutRule(TestClass testClass) { // Many protected convenience methods in BlockJUnit4ClassRunner that are available in JUnit 4.11 // such as getTestRules(Object) were not public until // https://github.com/junit-team/junit/commit/8782efa08abf5d47afdc16740678661443706740, // which appears to be JUnit 4.9. Because we allow users to use JUnit 4.7, we need to include a // custom implementation that is backwards compatible to JUnit 4.7. List<FrameworkField> fields = testClass.getAnnotatedFields(Rule.class); for (FrameworkField field : fields) { if (field.getField().getType().equals(Timeout.class)) { return true; } } return false; }
@Before public void init() throws Exception { sonarIssue = new DefaultIssue() .setKey("ABCD") .setMessage("The Cyclomatic Complexity of this method is 14 which is greater than 10 authorized.") .setSeverity("MINOR") .setRuleKey(RuleKey.of("squid", "CycleBetweenPackages")); ruleFinder = mock(RuleFinder.class); when(ruleFinder.findByKey(RuleKey.of("squid", "CycleBetweenPackages"))).thenReturn(org.sonar.api.rules.Rule.create().setName("Avoid cycle between java packages")); settings = new Settings(new PropertyDefinitions(JiraIssueCreator.class, JiraPlugin.class)); settings.setProperty(CoreProperties.SERVER_BASE_URL, "http://my.sonar.com"); settings.setProperty(JiraConstants.SERVER_URL_PROPERTY, "http://my.jira.com"); settings.setProperty(JiraConstants.USERNAME_PROPERTY, "foo"); settings.setProperty(JiraConstants.PASSWORD_PROPERTY, "bar"); settings.setProperty(JiraConstants.JIRA_PROJECT_KEY_PROPERTY, "TEST"); jiraIssueCreator = new JiraIssueCreator(ruleFinder); }
@Test public void shouldInitRemoteIssueWithoutName() throws Exception { // Given that when(ruleFinder.findByKey(RuleKey.of("squid", "CycleBetweenPackages"))).thenReturn(org.sonar.api.rules.Rule.create().setName(null)); RemoteIssue expectedIssue = new RemoteIssue(); expectedIssue.setProject("TEST"); expectedIssue.setType("3"); expectedIssue.setPriority("4"); expectedIssue.setSummary("Sonar Issue - CycleBetweenPackages"); //expectedIssue.setSummary("Sonar Issue #ABCD"); expectedIssue.setDescription("Issue detail:\n{quote}\nThe Cyclomatic Complexity of this method is 14 which is greater than 10 authorized.\n" + "{quote}\n\n\nCheck it on Sonar: http://my.sonar.com/issue/show/ABCD"); // Verify RemoteIssue returnedIssue = jiraIssueCreator.initRemoteIssue(sonarIssue, settings, ""); assertThat(returnedIssue.getSummary()).isEqualTo(expectedIssue.getSummary()); assertThat(returnedIssue.getDescription()).isEqualTo(expectedIssue.getDescription()); assertThat(returnedIssue).isEqualTo(expectedIssue); }
/** * @return {@code true} if the test class has any fields annotated with {@code Rule} whose type is * {@link Timeout}. */ static boolean hasTimeoutRule(TestClass testClass) { // Many protected convenience methods in BlockJUnit4ClassRunner that are available in JUnit 4.11 // such as getTestRules(Object) were not public until // https://github.com/junit-team/junit/commit/8782efa08abf5d47afdc16740678661443706740, // which appears to be JUnit 4.9. Because we allow users to use JUnit 4.7, we need to include a // custom implementation that is backwards compatible to JUnit 4.7. List<FrameworkField> fields = testClass.getAnnotatedFields(Rule.class); for (FrameworkField field : fields) { if (field.getField().getType().equals(Timeout.class)) { return true; } } return false; }
@Test public void get_all_classes_by_LocationProvider() { JavaClasses classes = cache.getClassesToAnalyzeFor(TestClassWithLocationProviders.class); assertThatClasses(classes).contain(String.class, Rule.class, getClass()); classes = cache.getClassesToAnalyzeFor(TestClassWithLocationProviderUsingTestClass.class); assertThatClasses(classes).contain(String.class); assertThatClasses(classes).dontContain(getClass()); }
@Test public void imports_the_classpath() { JavaClasses classes = new ClassFileImporter().importClasspath(); assertThatClasses(classes).contain(ClassFileImporter.class, getClass()); assertThatClasses(classes).dontContain(Rule.class); // Default doesn't import jars classes = new ClassFileImporter().importClasspath(new ImportOptions()); assertThatClasses(classes).contain(ClassFileImporter.class, getClass(), Rule.class); }
@Test public void imports_packages() { JavaClasses classes = new ClassFileImporter().importPackages( getClass().getPackage().getName(), Rule.class.getPackage().getName()); assertThatClasses(classes).contain(ImmutableSet.of(getClass(), Rule.class)); classes = new ClassFileImporter().importPackages( ImmutableSet.of(getClass().getPackage().getName(), Rule.class.getPackage().getName())); assertThatClasses(classes).contain(ImmutableSet.of(getClass(), Rule.class)); }
@Test public void imports_packages_of_classes() { JavaClasses classes = new ClassFileImporter().importPackagesOf(getClass(), Rule.class); assertThatClasses(classes).contain(ImmutableSet.of(getClass(), Rule.class)); classes = new ClassFileImporter().importPackagesOf(ImmutableSet.of(getClass(), Rule.class)); assertThatClasses(classes).contain(ImmutableSet.of(getClass(), Rule.class)); }
@Test public void imports_jars() throws Exception { JavaClasses classes = new ClassFileImporter().importJar(jarFileOf(Rule.class)); assertThatClasses(classes).contain(Rule.class); assertThatClasses(classes).dontContain(Object.class, ImmutableList.class); classes = new ClassFileImporter().importJars(jarFileOf(Rule.class), jarFileOf(ImmutableList.class)); assertThatClasses(classes).contain(Rule.class, ImmutableList.class); assertThatClasses(classes).dontContain(Object.class); classes = new ClassFileImporter().importJars(ImmutableList.of( jarFileOf(Rule.class), jarFileOf(ImmutableList.class))); assertThatClasses(classes).contain(Rule.class, ImmutableList.class); assertThatClasses(classes).dontContain(Object.class); }
@Test public void ImportOptions_are_respected() throws Exception { ClassFileImporter importer = new ClassFileImporter().withImportOption(importOnly(getClass(), Rule.class)); assertThatClasses(importer.importPath(Paths.get(urlOf(getClass()).toURI()))).matchExactly(getClass()); assertThatClasses(importer.importUrl(urlOf(getClass()))).matchExactly(getClass()); assertThatClasses(importer.importJar(jarFileOf(Rule.class))).matchExactly(Rule.class); }
@Test public void annotation() { String message = new ExceptionMessageBuilder("test") .annotation(Rule.class) .build(); assertThat(message, is("test\n - annotation: org.junit.Rule")); }
public JpaUnitRunner(final Class<?> clazz) throws InitializationError { super(clazz); executor = new DecoratorExecutor(); final List<FrameworkField> ruleFields = getTestClass().getAnnotatedFields(Rule.class); if (ruleFields.stream().anyMatch(f -> f.getType().equals(JpaUnitRule.class))) { throw new InitializationError("JpaUnitRunner and JpaUnitRule exclude each other"); } }
@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 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 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()); try { // WHEN new JpaUnitRule(cut); fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException e) { // THEN assertThat(e.getMessage(), containsString("EntityManagerFactory or EntityManager field annotated")); } }
@Test public void testClassWithMultiplePersistenceContextFields() 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 em1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em1"); em1Field.annotate(PersistenceContext.class); final JFieldVar em2Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em2"); em2Field.annotate(PersistenceContext.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()); try { // WHEN new JpaUnitRule(cut); fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException e) { // THEN assertThat(e.getMessage(), containsString("Only single field is allowed")); } }
@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 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 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()); try { // WHEN new JpaUnitRule(cut); fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException e) { // THEN assertThat(e.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 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 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()); try { // WHEN new JpaUnitRule(cut); fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException e) { // THEN assertThat(e.getMessage(), containsString("either @PersistenceUnit or @PersistenceContext")); } }
@Test public void testClassWithPersistenceContextFieldOfWrongType() 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, "em"); emField.annotate(PersistenceContext.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()); try { // WHEN new JpaUnitRule(cut); fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException e) { // THEN assertThat(e.getMessage(), containsString("annotated with @PersistenceContext is not of type EntityManager")); } }
@Test public void testClassWithPersistenceUnitFieldOfWrongType() 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, "emf"); emField.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()); try { // WHEN new JpaUnitRule(cut); fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException e) { // THEN assertThat(e.getMessage(), containsString("annotated with @PersistenceUnit is not of type EntityManagerFactory")); } }
@Test public void testClassWithPersistenceContextWithoutUnitNameSpecified() 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"); emField.annotate(PersistenceContext.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()); try { // WHEN new JpaUnitRule(cut); fail("JpaUnitException expected"); } catch (final JpaUnitException e) { // THEN assertThat(e.getMessage(), containsString("No Persistence")); } }
@Test public void testClassWithPersistenceUnitWithoutUnitNameSpecified() 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"); emField.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()); try { // WHEN new JpaUnitRule(cut); fail("JpaUnitException expected"); } catch (final JpaUnitException e) { // THEN assertThat(e.getMessage(), containsString("No Persistence")); } }
@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 testJpaUnitRunnerAndJpaUnitRuleFieldExcludeEachOther() 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 emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf"); final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.class); jAnnotation.param("unitName", "test-unit-1"); final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule"); ruleField.annotate(Rule.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()); try { // WHEN new JpaUnitRunner(cut); fail("InitializationError expected"); } catch (final InitializationError e) { // expected assertThat(e.getCauses().get(0).getMessage(), containsString("exclude each other")); } }
private TypeSpec classTest(ClassName className, List<MethodSpec> methodSpecs) { String methodName = Introspector .decapitalize(className.simpleName()); MethodSpec abstractMethodInstanceToTest = methodBuilder(methodName) .addModifiers(Modifier.ABSTRACT, Modifier.PROTECTED) .returns(className) .build(); FieldSpec exception = FieldSpec.builder(ExpectedException.class, "exception") .addAnnotation(Rule.class) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .initializer("$T.none()", ExpectedException.class) .build(); return TypeSpec.classBuilder(className.simpleName() + "Test_") .addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC) .addMethod(abstractMethodInstanceToTest) .addField(exception) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", MockeryProcessor.class.getCanonicalName()) .addMember("comments", "$S", CMessages.codeGenerateWarning()) .build()) .addAnnotation(AnnotationSpec.builder(RunWith.class) .addMember("value", "$T.class", OrderedRunner.class) .build()) .addMethods(methodSpecs) .build(); }
/** * @param target the test case instance * @return a list of TestRules that should be applied when executing this * test */ protected List<TestRule> getTestRules(Object target) { List<TestRule> result = getTestClass().getAnnotatedMethodValues(target, Rule.class, TestRule.class); result.addAll(getTestClass().getAnnotatedFieldValues(target, Rule.class, TestRule.class)); return result; }
@Override public void executeTest(final Method method, final Object testInstance, final Runnable test) { // We change the context classloader to the current CL in order for the Mockito // framework to load it's plugins (such as MockMaker) correctly. final ClassLoader originalCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); final Set<Field> rules; try { rules = Whitebox.getFieldsAnnotatedWith( testInstance, Rule.class ); } finally { Thread.currentThread().setContextClassLoader(originalCL); } hasRules = !rules.isEmpty(); if (!hasRules) { executeTestInSuper(method, testInstance, test); } else { int processedFields = 0; for (Field field : rules) { processedFields++; try { LastRuleTestExecutorStatement lastStatement = new LastRuleTestExecutorStatement(processedFields, rules.size(), test, testInstance, method); Statement statement = applyRuleToLastStatement(method, testInstance, field, lastStatement); statement.evaluate(); } catch (Throwable e) { /* * No rule could handle the exception thus we need to * add it as a failure. */ super.handleException(testMethod, potentialTestFailure == null ? e : potentialTestFailure); } } } }
/** * Load classes (TestCase, @Before and @After with custom class loader. * * @throws ClassNotFoundException the class not found exception */ private void loadClassesWithCustomClassLoader( FrameworkMethod method ) throws ClassNotFoundException { // We need the classpath so that our custom loader can search for the requested classes. String testPath = getClassPath(); TestClassLoader classLoader = testPath == null ? new TestClassLoader() : new TestClassLoader( testPath ); ClptrExclude clptrExclude = getTestClass().getAnnotation( ClptrExclude.class ); if ( clptrExclude != null ) { classLoader.addExcludes( clptrExclude.value() ); } clptrExclude = method.getAnnotation( ClptrExclude.class ); if ( clptrExclude != null ) { classLoader.addExcludes(clptrExclude.value() ); } Thread.currentThread().setContextClassLoader(classLoader); testClassFromClassLoader = new TestClass(classLoader.loadClass(getTestClass().getJavaClass().getName())); // See withAfters and withBefores for the reason. beforeFromClassLoader = classLoader.loadClass(Before.class.getName()); afterFromClassLoader = classLoader.loadClass(After.class.getName()); ruleFromClassLoader = classLoader.loadClass(Rule.class.getName()); }
@Test public void shouldUpdateFormFieldVisibilityRules() throws Exception { VisibilityRules visibilityRule = new VisibilityRules(); visibilityRule.setRuleType(RuleType.SHOW); List<VisibilityRules.Rule> rules = Collections.singletonList(rule("FirstName", "isNotEmpty", "Der address")); visibilityRule.setRules(rules); marketoFormClient.updateFormFieldVisibilityRules(TEST_FORM_ID, TEST_FORM_FIELD, visibilityRule); // Can not verify - no way to fetch not approved content }
@Rule public Recorder createRecorder() { Recorder recorder = new Recorder(); String tc = this.getClass().getSimpleName(); recorder.setTapeRoot(new File(recorder.getTapeRoot(), (tc).substring(0, tc.length() - "Test".length()))); return recorder; }
/** * Creates a test rule. * * @return a test rule. */ @Rule public TestRule rule() { return RuleChain .outerRule(new LogbackAccessEventQueuingAppenderRule()) .around(new LogbackAccessEventQueuingListenerRule()); }