org.junit.runner.RunWith Java Examples

The following examples show how to use org.junit.runner.RunWith. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DesugarRuleBuilder.java    From bazel with Apache License 2.0 6 votes vote down vote up
DesugarRuleBuilder(Object testInstance, MethodHandles.Lookup testInstanceLookup) {
  this.testInstance = testInstance;
  this.testInstanceLookup = testInstanceLookup;
  Class<?> testClass = testInstance.getClass();

  androidRuntimeJarJvmFlagValue = getExplicitJvmFlagValue(ANDROID_RUNTIME_JAR_JVM_FLAG_KEY);
  jacocoAgentJarJvmFlagValue = getExplicitJvmFlagValue(JACOCO_AGENT_JAR_JVM_FLAG_KEY);

  if (testClass != testInstanceLookup.lookupClass()) {
    errorMessenger.addError(
        "Expected testInstanceLookup has private access to (%s), but get (%s). Have you"
            + " passed MethodHandles.lookup() to testInstanceLookup in test class?",
        testClass, testInstanceLookup.lookupClass());
  }
  if (!testClass.isAnnotationPresent(RunWith.class)) {
    errorMessenger.addError(
        "Expected a test instance whose class is annotated with @RunWith. %s", testClass);
  }

  injectableClassLiterals =
      findAllInjectableFieldsWithQualifier(testClass, DynamicClassLiteral.class);
  injectableAsmNodes = findAllInjectableFieldsWithQualifier(testClass, AsmNode.class);
  injectableMethodHandles =
      findAllInjectableFieldsWithQualifier(testClass, RuntimeMethodHandle.class);
  injectableJarEntries = findAllInjectableFieldsWithQualifier(testClass, RuntimeJarEntry.class);
}
 
Example #2
Source File: SquidbTestRunner.java    From squidb with Apache License 2.0 6 votes vote down vote up
/**
 * @return true if {@param cls} is {@link JUnit4} annotated.
 */
protected boolean isJUnit4TestClass(Class cls) {
    // Need to find test classes, otherwise crashes with b/11790448.
    if (!cls.getName().endsWith("Test")) {
        return false;
    }
    // Check the annotations.
    Annotation annotation = cls.getAnnotation(RunWith.class);
    if (annotation != null) {
        RunWith runWith = (RunWith) annotation;
        Object value = runWith.value();
        if (value.equals(JUnit4.class) || value.equals(Suite.class)) {
            return true;
        }
    }
    return false;
}
 
Example #3
Source File: ClassScannerTest.java    From gadtry with Apache License 2.0 5 votes vote down vote up
@Test
public void getFilterTest()
{
    ClassScanner scanner = ClassScanner.builder("com.github.harbby.gadtry").scan();

    Set<Class<?>> classSet = scanner.getClassWithAnnotated(RunWith.class, Deprecated.class);
    Assert.assertTrue(classSet.contains(ClassScannerTest.class));

    classSet = scanner.getClassWithSubclassOf(Serializable.class);
    Assert.assertTrue(classSet.contains(ClassScannerTest.class));
    for (Class<?> aClass : classSet) {
        Assert.assertTrue(Serializable.class.isAssignableFrom(aClass));
    }
}
 
Example #4
Source File: TestRunnerUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public static boolean isJUnit4TestClass(final Class aClass) {
  final int modifiers = aClass.getModifiers();
  if ((modifiers & Modifier.ABSTRACT) != 0) return false;
  if ((modifiers & Modifier.PUBLIC) == 0) return false;
  if (aClass.getAnnotation(RunWith.class) != null) return true;
  for (Method method : aClass.getMethods()) {
    if (method.getAnnotation(Test.class) != null) return true;
  }
  return false;
}
 
Example #5
Source File: OptionDefaultValueConversionTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static boolean isTestClass(Class<?> initialClazz) {
  Class<?> clazz = initialClazz;
  do {
    if (clazz.isAnnotationPresent(RunWith.class)) {
      logger.atFiner().log("Filtered out %s: is a Test class", initialClazz);
      return true;
    }
    clazz = clazz.getEnclosingClass();
  } while (clazz != null);

  return false;
}
 
Example #6
Source File: JUnit4SuiteFinder.java    From pitest with Apache License 2.0 5 votes vote down vote up
private boolean hasSuitableRunnner(final Class<?> clazz) {

    final RunWith runWith = clazz.getAnnotation(RunWith.class);
    if (runWith != null) {
      return (runWith.value().equals(Suite.class));
    }
    return false;
  }
 
Example #7
Source File: HBaseClassTestRule.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * @param clazz Test class that is running.
 * @return the number of parameters for this given test class. If the test is not parameterized or
 *   if there is any issue determining the number of parameters, returns 1.
 */
@VisibleForTesting
static int getNumParameters(Class<?> clazz) {
  RunWith[] runWiths = clazz.getAnnotationsByType(RunWith.class);
  boolean testParameterized = runWiths != null && Arrays.stream(runWiths).anyMatch(
    (r) -> r.value().equals(Parameterized.class));
  if (!testParameterized) {
    return 1;
  }
  for (Method method : clazz.getMethods()) {
    if (!isParametersMethod(method)) {
      continue;
    }
    // Found the parameters method. Figure out the number of parameters.
    Object parameters;
    try {
      parameters = method.invoke(clazz);
    } catch (IllegalAccessException | InvocationTargetException e) {
      LOG.warn("Error invoking parameters method {} in test class {}",
          method.getName(), clazz, e);
      continue;
    }
    if (parameters instanceof List) {
      return  ((List) parameters).size();
    } else if (parameters instanceof Collection) {
      return  ((Collection) parameters).size();
    } else if (parameters instanceof Iterable) {
      return Iterables.size((Iterable) parameters);
    } else if (parameters instanceof Object[]) {
      return ((Object[]) parameters).length;
    }
  }
  LOG.warn("Unable to determine parameters size. Returning the default of 1.");
  return 1;
}
 
Example #8
Source File: SqlIntegrationMembershipTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void sqlIntegrationMembershipComplete() {
  ImmutableSet<String> sqlDependentTests;
  try (ScanResult scanResult =
      new ClassGraph().enableAnnotationInfo().whitelistPackages("google.registry").scan()) {
    sqlDependentTests =
        scanResult.getClassesWithAnnotation(RunWith.class.getName()).stream()
            .filter(clazz -> clazz.getSimpleName().endsWith("Test"))
            .map(clazz -> clazz.loadClass())
            .filter(SqlIntegrationMembershipTest::isSqlDependent)
            .map(Class::getName)
            .collect(ImmutableSet.toImmutableSet());
  }
  ImmutableSet<String> declaredTests =
      Stream.of(SqlIntegrationTestSuite.class.getAnnotation(SuiteClasses.class).value())
          .map(Class::getName)
          .collect(ImmutableSet.toImmutableSet());
  SetView<String> undeclaredTests = Sets.difference(sqlDependentTests, declaredTests);
  expect
      .withMessage(
          "Undeclared sql-dependent tests found. "
              + "Please add them to SqlIntegrationTestSuite.java.")
      .that(undeclaredTests)
      .isEmpty();
  SetView<String> unnecessaryDeclarations = Sets.difference(declaredTests, sqlDependentTests);
  expect
      .withMessage("Found tests that should not be included in SqlIntegrationTestSuite.java.")
      .that(unnecessaryDeclarations)
      .isEmpty();
}
 
Example #9
Source File: BrewJavaFile.java    From Mockery with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #10
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@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"));
    }

}
 
Example #11
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@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 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 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 JpaUnitRunner runner = new JpaUnitRunner(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"));
}
 
Example #12
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@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 JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    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 JpaUnitRunner runner = new JpaUnitRunner(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"));
}
 
Example #13
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@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 JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    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());

    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(JpaUnitException.class));
    assertThat(failure.getException().getMessage(), containsString("No Persistence"));
}
 
Example #14
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@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 JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    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());

    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(JpaUnitException.class));
    assertThat(failure.getException().getMessage(), containsString("No Persistence"));
}
 
Example #15
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@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 JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    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());

    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("annotated with @PersistenceUnit is not of type EntityManagerFactory"));
}
 
Example #16
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example #17
Source File: ClassScannerTest.java    From gadtry with Apache License 2.0 5 votes vote down vote up
@Test
public void scanTest()
{
    ClassScanner scanner = ClassScanner.builder("com.github.harbby.gadtry")
            .subclassOf(Serializable.class)
            .annotated(RunWith.class)
            .classLoader(this.getClass().getClassLoader())
            .filter(aClass -> !aClass.isEnum())
            .scan();
    Set<Class<?>> classSet = scanner.getClasses();
    Assert.assertTrue(!classSet.isEmpty());
    Assert.assertTrue(classSet.contains(ClassScannerTest.class));
}
 
Example #18
Source File: ClassPathTestScanner.java    From COLA with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean isColaTestClass(Class<?> testClzz){
    RunWith runWith = testClzz.getAnnotation(RunWith.class);
    if(runWith == null){
        return false;
    }
    if(runWith.value().equals(ColaTestRunner.class)
        || runWith.value().equals(ColaTestUnitRunner.class)){
        return true;
    }
    return false;
}
 
Example #19
Source File: GuidedFuzzing.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Runs the guided fuzzing loop for a resolved class.
 *
 * <p>The test class must be annotated with <tt>@RunWith(JQF.class)</tt>
 * and the test method must be annotated with <tt>@Fuzz</tt>.</p>
 *
 * <p>Once this method is invoked, the guided fuzzing loop runs continuously
 * until the guidance instance decides to stop by returning <tt>false</tt>
 * for {@link Guidance#hasInput()}. Until the fuzzing stops, this method
 * cannot be invoked again (i.e. at most one guided fuzzing can be running
 * at any time in a single JVM instance).</p>
 *
 * @param testClass     the test class containing the test method
 * @param testMethod    the test method to execute in the fuzzing loop
 * @param guidance      the fuzzing guidance
 * @param out           an output stream to log Junit messages
 * @throws IllegalStateException if a guided fuzzing run is currently executing
 * @return the Junit-style test result
 */
public synchronized static Result run(Class<?> testClass, String testMethod,
                                      Guidance guidance, PrintStream out) throws IllegalStateException {

    // Ensure that the class uses the right test runner
    RunWith annotation = testClass.getAnnotation(RunWith.class);
    if (annotation == null || !annotation.value().equals(JQF.class)) {
        throw new IllegalArgumentException(testClass.getName() + " is not annotated with @RunWith(JQF.class)");
    }


    // Set the static guided instance
    setGuidance(guidance);

    // Register callback
    SingleSnoop.setCallbackGenerator(guidance::generateCallBack);

    // Create a JUnit Request
    Request testRequest = Request.method(testClass, testMethod);

    // Instantiate a runner (may return an error)
    Runner testRunner = testRequest.getRunner();

    // Start tracing for the test method
    SingleSnoop.startSnooping(testClass.getName() + "#" + testMethod);

    // Run the test and make sure to de-register the guidance before returning
    try {
        JUnitCore junit = new JUnitCore();
        if (out != null) {
            junit.addListener(new TextListener(out));
        }
        return junit.run(testRunner);
    } finally {
        unsetGuidance();
    }



}
 
Example #20
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void imports_urls_of_jars() {
    Set<URL> urls = newHashSet(urlOf(Test.class), urlOf(RunWith.class));
    assumeTrue("We can't completely ensure that this will always be taken from a JAR file, though it's very likely",
            "jar".equals(urls.iterator().next().getProtocol()));

    JavaClasses classes = new ClassFileImporter().importUrls(urls)
            .that(DescribedPredicate.not(type(Annotation.class))); // NOTE @Test and @RunWith implement Annotation.class

    assertThat(classes).as("Number of classes at the given URLs").hasSize(2);
}
 
Example #21
Source File: CustomParameterizedBlockJUnit4Runner.java    From registry with Apache License 2.0 5 votes vote down vote up
@Override
protected Annotation[] getRunnerAnnotations() {
    Annotation[] allAnnotations = super.getRunnerAnnotations();
    Annotation[] annotationsWithoutRunWith = new Annotation[allAnnotations.length - 1];
    int i = 0;
    for (Annotation annotation: allAnnotations) {
        if (!annotation.annotationType().equals(RunWith.class)) {
            annotationsWithoutRunWith[i] = annotation;
            ++i;
        }
    }
    return annotationsWithoutRunWith;
}
 
Example #22
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example #23
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@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 JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    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());

    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("annotated with @PersistenceContext is not of type EntityManager"));
}
 
Example #24
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example #25
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@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 JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    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());

    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"));
}
 
Example #26
Source File: CustomParameterizedBlockJUnit4Runner.java    From registry with Apache License 2.0 5 votes vote down vote up
@Override
protected Annotation[] getRunnerAnnotations() {
    Annotation[] allAnnotations = super.getRunnerAnnotations();
    Annotation[] annotationsWithoutRunWith = new Annotation[allAnnotations.length - 1];
    int i = 0;
    for (Annotation annotation: allAnnotations) {
        if (!annotation.annotationType().equals(RunWith.class)) {
            annotationsWithoutRunWith[i] = annotation;
            ++i;
        }
    }
    return annotationsWithoutRunWith;
}
 
Example #27
Source File: TestSuiteBuilder.java    From bazel-buildfarm with Apache License 2.0 4 votes vote down vote up
/**
 * Classes that have a {@code RunWith} annotation for {@link Suite} or are automatically excluded
 * to avoid picking up the suite class itself.
 */
private static boolean isSuite(Class<?> container) {
  RunWith runWith = container.getAnnotation(RunWith.class);
  return (runWith != null) && ((runWith.value() == CustomSuite.class));
}
 
Example #28
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 4 votes vote down vote up
@Test
public void testClassWithPersistenceContextWithWithOverwrittenConfiguration() 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, EntityManager.class, "em");
    final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class);
    jAnnotation.param("unitName", "test-unit-1");
    final JAnnotationArrayMember propArray = jAnnotation.paramArray("properties");
    propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.url").param("value",
            "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
    propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.driver").param("value", "org.h2.Driver");
    propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.password").param("value", "test");
    propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.user").param("value", "test");
    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 JpaUnitRunner runner = new JpaUnitRunner(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"));
}
 
Example #29
Source File: JUnitRunner.java    From buck with Apache License 2.0 4 votes vote down vote up
/** Guessing whether or not a class is a test class is an imperfect art form. */
private boolean mightBeATestClass(Class<?> klass) {
  if (klass.getAnnotation(RunWith.class) != null) {
    return true; // If the class is explicitly marked with @RunWith, it's a test class.
  }
  // Since no RunWith annotation, using standard runner, which requires
  // test classes to be non-abstract/non-interface
  int klassModifiers = klass.getModifiers();
  if (Modifier.isInterface(klassModifiers) || Modifier.isAbstract(klassModifiers)) {
    return false;
  }

  // Classes that extend junit.framework.TestCase are JUnit3-style test classes.
  if (TestCase.class.isAssignableFrom(klass)) {
    return true;
  }

  // Since no RunWith annotation, using standard runner, which requires
  // test classes to have exactly one public constructor (that has no args).
  // Classes may have (non-public) constructors (with or without args).
  boolean foundPublicNoArgConstructor = false;
  for (Constructor<?> c : klass.getConstructors()) {
    if (Modifier.isPublic(c.getModifiers())) {
      if (c.getParameterCount() != 0) {
        return false;
      }
      foundPublicNoArgConstructor = true;
    }
  }
  if (!foundPublicNoArgConstructor) {
    return false;
  }
  // If the class has a JUnit4 @Test-annotated method, it's a test class.
  boolean hasAtLeastOneTest = false;
  for (Method m : klass.getMethods()) {
    if (Modifier.isPublic(m.getModifiers())
        && m.getParameters().length == 0
        && m.getAnnotation(Test.class) != null) {
      hasAtLeastOneTest = true;
      break;
    }
  }
  return hasAtLeastOneTest;
}
 
Example #30
Source File: ArquillianJUnitTransformer.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
protected boolean isAlreadyTransformed(CtClass clazz) throws Exception {
    return clazz.hasAnnotation(RunWith.class);
}