Java 类org.junit.Rule 实例源码

项目:GitHub    文件:Jsonschema2PojoRuleTest.java   
@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;
        }
    };
}
项目:ArchUnit    文件:ClassFileImporterTest.java   
@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);
}
项目:ArchUnit    文件:CanBeAnnotatedTest.java   
@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");
}
项目:spring4-understanding    文件:SpringClassRule.java   
/**
 * 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));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
}
项目:DaggerMock    文件:OverriddenObjectsMap.java   
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);
                }
            }
        }
    }
}
项目:rise    文件:WebTestBase.java   
@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
                    }
            }
        }
    };
}
项目:DaggerMock    文件:OverriddenObjectsMap.java   
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);
                }
            }
        }
    }
}
项目:scott    文件:StateTrackingTestClassVisitor.java   
@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();
}
项目:buck-cutom    文件:BuckBlockJUnit4ClassRunner.java   
/**
 * @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;
}
项目:caltec-tools    文件:JiraIssueCreatorTest.java   
@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);
}
项目:caltec-tools    文件:JiraIssueCreatorTest.java   
@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);
}
项目:buck    文件:BuckBlockJUnit4ClassRunner.java   
/**
 * @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;
}
项目:ArchUnit    文件:ClassCacheTest.java   
@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());
}
项目:ArchUnit    文件:ClassFileImporterSlowTest.java   
@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);
}
项目:ArchUnit    文件:ClassFileImporterSlowTest.java   
@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));
}
项目:ArchUnit    文件:ClassFileImporterSlowTest.java   
@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));
}
项目:ArchUnit    文件:ClassFileImporterSlowTest.java   
@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);
}
项目:ArchUnit    文件:ClassFileImporterTest.java   
@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);
}
项目:Spork    文件:ExceptionMessageBuilderTests.java   
@Test
public void annotation() {
    String message = new ExceptionMessageBuilder("test")
            .annotation(Rule.class)
            .build();

    assertThat(message, is("test\n - annotation: org.junit.Rule"));
}
项目:jpa-unit    文件:JpaUnitRunner.java   
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");
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
}
项目:jpa-unit    文件:JpaUnitRunnerTest.java   
@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"));
    }

}
项目:Mockery    文件:BrewJavaFile.java   
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();
}
项目:kc-rice    文件:LoadTimeWeavableTestRunner.java   
/**
 * @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;
}
项目:powermock    文件:PowerMockJUnit47RunnerDelegateImpl.java   
@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);
            }
        }
    }
}
项目:junit-clptr    文件:ClassLoaderPerTestRunner.java   
/**
 * 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());
}
项目:marketo-rest-sdk-java    文件:FormIntegrationTest.java   
@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
}
项目:currencycloud-java    文件:BetamaxTestSupport.java   
@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;
}
项目:logback-access-spring-boot-starter    文件:AbstractTestSpringConfigurationFileAutoDetectingTest.java   
/**
 * Creates a test rule.
 *
 * @return a test rule.
 */
@Rule
public TestRule rule() {
    return RuleChain
            .outerRule(new LogbackAccessEventQueuingAppenderRule())
            .around(new LogbackAccessEventQueuingListenerRule());
}
项目:logback-access-spring-boot-starter    文件:AbstractForwardHeadersUsingTest.java   
/**
 * Creates a test rule.
 *
 * @return a test rule.
 */
@Rule
public TestRule rule() {
    return RuleChain
            .outerRule(new LogbackAccessEventQueuingAppenderRule())
            .around(new LogbackAccessEventQueuingListenerRule());
}
项目:logback-access-spring-boot-starter    文件:AbstractSecurityAttributesTest.java   
/**
 * Creates a test rule.
 *
 * @return a test rule.
 */
@Rule
public TestRule rule() {
    return RuleChain
            .outerRule(new LogbackAccessEventQueuingAppenderRule())
            .around(new LogbackAccessEventQueuingListenerRule());
}