Java Code Examples for org.junit.runner.RunWith

The following are top voted examples for showing how to use org.junit.runner.RunWith. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: willtest   File: SuiteGeneratingRunListener.java   View source code 6 votes vote down vote up
@Override
public void testRunFinished(Result result) throws Exception {
    super.testRunFinished(result);
    JCodeModel codeModel = new JCodeModel();
    JDefinedClass resultClass = codeModel._class(getSuiteClassName());
    JClass suiteClazz = codeModel.ref(Suite.class);
    resultClass.annotate(RunWith.class).param(VALUE_PARAM, suiteClazz);

    JClass suiteClasses = codeModel.ref(Suite.SuiteClasses.class);

    JAnnotationArrayMember testClassArray = resultClass.annotate(suiteClasses).paramArray(VALUE_PARAM);

    testClassesAndTheirTests.keySet().forEach(className -> addClassToSuite(codeModel, testClassArray, className));

    resultClass.javadoc().add(getJavaDocComment());

    File file = new File(getTargetDirectory());
    if ( !file.exists() && !file.mkdirs() ) {
        throw new RuntimeException("Cannot create folder " + file.getAbsolutePath());
    }
    codeModel.build(file);
}
 
Example 2
Project: core-doppl   File: DopplJunitTestHelper.java   View source code 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
Project: spring-web-api-test-stubber   File: SpringBootRestControllerTesterStubGenerator.java   View source code 6 votes vote down vote up
private TypeSpec buildTypeSpec(List<MethodSpec> methodSpecs, List<FieldSpec> fieldSpecs, MethodSpec setUp) {

        return TypeSpec.classBuilder(this.restControllerModel.getSimpleClassName())
                .addAnnotation(Transactional.class)
                .addAnnotation(
                        AnnotationSpec.builder(RunWith.class)
                                      .addMember("value", "$T.class", SpringJUnit4ClassRunner.class)
                                      .build()
                )
                .addAnnotation(
                        AnnotationSpec.builder(ComponentScan.class)
                                      .addMember("basePackages", "{$S, $S}", "YOUR_DTOs_PACKAGE", "YOUR_SERVICEs_PACKAGE")
                                      .build()
                )
                .addAnnotation(SpringBootTest.class)
                .addModifiers(Modifier.PUBLIC)
                .addFields(fieldSpecs)
                .addMethod(setUp)
                .addMethods(methodSpecs)
                .build();
    }
 
Example 4
Project: j2objc   File: JUnitTestRunner.java   View source code 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;
    if (runWith.value().equals(JUnit4.class)) {
      return true;
    }
  }
  return false;
}
 
Example 5
Project: cloudera-framework   File: CdhServer.java   View source code 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "LoopStatementThatDoesntLoop"})
private boolean assertTestRunner(String testClass) {
  try {
    RunWith runWith = Class.forName(testClass).getAnnotation(RunWith.class);
    if (runWith == null) {
      throw new RuntimeException("Missing [@" + RunWith.class.getCanonicalName() + "(" + TestRunner.class.getCanonicalName()
        + ".class)] on class [" + testClass + "]");
    }
    if (runWith.value().equals(Suite.class)) {
      SuiteClasses suiteClasses = Class.forName(testClass).getAnnotation(SuiteClasses.class);
      for (Class suiteTestClass : suiteClasses.value()) {
        return assertTestRunner(suiteTestClass.getCanonicalName());
      }
    } else if (!runWith.value().equals(TestRunner.class)) {
      throw new RuntimeException("Unsupported run with [" + runWith.value().getCanonicalName() + "] on class [" + testClass + "]");
    }
  } catch (Exception exception) {
    String message = "The test [" + testClass + "] included a rule [" + getClass().getCanonicalName() + "] but did not include a [@"
      + RunWith.class.getCanonicalName() + "(" + TestRunner.class.getCanonicalName() + ".class)] class annotation";
    if (LOG.isErrorEnabled()) {
      LOG.error(message, exception);
    }
    throw new RuntimeException(message, exception);
  }
  return true;
}
 
Example 6
Project: squidb   File: SquidbTestRunner.java   View source code 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 7
Project: error-prone   File: JUnit4SetUpNotRunTest.java   View source code 6 votes vote down vote up
@Test
public void noBeforeOnClasspath() throws Exception {
  File libJar = tempFolder.newFile("lib.jar");
  try (FileOutputStream fis = new FileOutputStream(libJar);
      JarOutputStream jos = new JarOutputStream(fis)) {
    addClassToJar(jos, RunWith.class);
    addClassToJar(jos, JUnit4.class);
    addClassToJar(jos, BlockJUnit4ClassRunner.class);
    addClassToJar(jos, ParentRunner.class);
    addClassToJar(jos, SuperTest.class);
    addClassToJar(jos, SuperTest.class.getEnclosingClass());
  }
  compilationHelper
      .addSourceLines(
          "Test.java",
          "import org.junit.runner.RunWith;",
          "import org.junit.runners.JUnit4;",
          "import " + SuperTest.class.getCanonicalName() + ";",
          "@RunWith(JUnit4.class)",
          "class Test extends SuperTest {",
          "  @Override public void setUp() {}",
          "}")
      .setArgs(Arrays.asList("-cp", libJar.toString()))
      .doTest();
}
 
Example 8
Project: junit-converter   File: SuiteRewritingStage.java   View source code 6 votes vote down vote up
/**
 * @see junitconverter.stages.TestConversionStage#convertClass(junitconverter.testcase.TestCaseClass)
 */
public void convertClass(TestCaseClass testCase)
{
	// This is a gigantic hack. We use a regex to search for classes/suites added to the suite.
	// We start our search at the beginning of the suite method
	List<String> lines = testCase.getLines().subList(testCase.getSuiteStartLine(), testCase.getSuiteEndLine() + 1);
	StringBuilder builder = new StringBuilder();
	builder.append('{');
	for (String line : lines)
	{
		Matcher m = p.matcher(line);
		if (m.find())
		{
			String testName = m.group(2);
			builder.append(testName).append(".class, "); //$NON-NLS-1$
		}
	}
	builder.append('}');
	codeEditor.addAnnotation(testCase, SuiteClasses.class, builder.toString());
	codeEditor.addAnnotation(testCase, RunWith.class, "Suite.class"); //$NON-NLS-1$
}
 
Example 9
Project: jexunit   File: TestCommandScanner.java   View source code 6 votes vote down vote up
@Override
public void reportMethodAnnotation(Class<? extends Annotation> annotation, String className, String methodName) {
    try {
        Class<?> clazz = getClass().getClassLoader().loadClass(className);
        Class<?> type = null;
        if (clazz.isAnnotationPresent(RunWith.class)) {
            RunWith rwa = clazz.getAnnotation(RunWith.class);
            if (rwa.value() == JExUnit.class) {
                type = clazz;
            }
        }

        if (annotation.isAnnotation() && (annotation == TestCommand.class || annotation == TestCommands.class)) {
            for (Method m : clazz.getDeclaredMethods()) {
                TestCommand[] testCommands = m.getDeclaredAnnotationsByType(TestCommand.class);
                registerCommands(testCommands, type, m);
            }
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}
 
Example 10
Project: dynamic-extensions-testrunner   File: TestScanner.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Set<BundleTest> getTests() throws InvalidSyntaxException {
  final Set<BundleTest> allTests = new TreeSet<BundleTest>();
  final Bundle[] bundles = bundleContext.getBundles();
  for (Bundle bundle : bundles) {
    if (bundle.getState() == Bundle.ACTIVE) {
        if ("true".equalsIgnoreCase(bundle.getHeaders().get("Alfresco-Dynamic-Extension"))) {
            ApplicationContext applicationContext = ContextUtils.findApplicationContext(bundle.getSymbolicName());
            if (applicationContext != null) {
                Map<String,Object> testComponents = applicationContext.getBeansWithAnnotation(RunWith.class);
                logger.debug("Looking for JUnit tests in {}", bundle.getSymbolicName());
                for (Object test : testComponents.values()) {
                    BundleTest bundleTest = new BundleTest(test.getClass().getName(), bundle.getBundleId(), bundle.getSymbolicName());
                    logger.debug("Found test: {}", test);
                    allTests.add(bundleTest);
                }
            }
        }
    }
  }
  return allTests;
}
 
Example 11
Project: ArchUnit   File: ClassFileImporterTest.java   View source code 5 votes vote down vote up
@Test
public void imports_urls_of_jars() throws IOException {
    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 12
Project: monarch   File: CategoryWithParameterizedRunner.java   View source code 5 votes vote down vote up
@Override
public Annotation[] getRunnerAnnotations() {
  Annotation[] allAnnotations = getTestClass().getAnnotations();
  List<Annotation> annotationsWithoutRunWith = new ArrayList<>();
  for (Annotation annotation : allAnnotations) {
    if (!annotation.annotationType().equals(RunWith.class)) {
      annotationsWithoutRunWith.add(annotation);
    }
  }
  return annotationsWithoutRunWith.toArray(new Annotation[0]);
}
 
Example 13
Project: bobcat   File: PageObjectInterceptor.java   View source code 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
  Class<?> clazz = AopUtil.getBaseClassForAopObject(Class.forName(Thread.currentThread().getStackTrace()[8].
    getClassName()));
  if (clazz.isAnnotationPresent(RunWith.class) || clazz.isAnnotationPresent(ScenarioScoped.class)) {
    pageObjectInvocationTracker.clearStack();
  }
  if (methodInvocation.getMethod().getDeclaringClass().isAnnotationPresent(PageObject.class)) {
    pageObjectInvocationTracker.add(clazz, methodInvocation.getThis());
  }
  return methodInvocation.proceed();
}
 
Example 14
Project: bobcat   File: TestObjectTypeListener.java   View source code 5 votes vote down vote up
private <I> boolean isApplicable(Class<? super I> rawType) {
  boolean result;
  if (rawType.isAnnotationPresent(RunWith.class)
      && !rawType.isAnnotationPresent(CucumberOptions.class)) {
    result = true;
  } else {
    result = isStepsImplementationClass(rawType);
  }
  return result;
}
 
Example 15
Project: registry   File: CustomParameterizedBlockJUnit4Runner.java   View source code 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 16
Project: jpa-unit   File: JpaUnitRunnerTest.java   View source code 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 17
Project: jpa-unit   File: JpaUnitRunnerTest.java   View source code 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 18
Project: jpa-unit   File: JpaUnitRunnerTest.java   View source code 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 19
Project: jpa-unit   File: JpaUnitRunnerTest.java   View source code 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 20
Project: jpa-unit   File: JpaUnitRunnerTest.java   View source code 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 21
Project: jpa-unit   File: JpaUnitRunnerTest.java   View source code 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 22
Project: jpa-unit   File: JpaUnitRunnerTest.java   View source code 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 23
Project: jpa-unit   File: JpaUnitRunnerTest.java   View source code 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 24
Project: jpa-unit   File: JpaUnitRunnerTest.java   View source code 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 25
Project: jpa-unit   File: JpaUnitRunnerTest.java   View source code 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 26
Project: Mockery   File: BrewJavaFile.java   View source code 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 27
Project: singular-server   File: SingularServerSpringMockitoTestConfig.java   View source code 5 votes vote down vote up
public SingularServerSpringMockitoTestConfig(Object myTestClass) {
    if (myTestClass.getClass().isAnnotationPresent(RunWith.class)) {
        Class<? extends Runner> runnerClass = myTestClass.getClass().getDeclaredAnnotation(RunWith.class).value();
        if (runnerClass.isAssignableFrom(MockitoJUnitRunner.class)) {
            this.myTestClass = myTestClass;
            return;
        }
    }
    throw new IllegalArgumentException(this.getClass().getName() + " somente funciona com classes de teste cujo runner seja do tipo: " + MockitoJUnitRunner.class.getName());
}
 
Example 28
Project: intellij-ce-playground   File: TestRunnerUtil.java   View source code 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 29
Project: junit-composite-runner   File: ExampleTest.java   View source code 5 votes vote down vote up
@Test
public void testAnnotationsRetained() throws Throwable {
    Class<?> proxyClass = getClass();

    RunWith annotation = proxyClass.getAnnotation(RunWith.class);
    Assert.assertNotNull(annotation);
    Assert.assertEquals(CompositeRunner.class, annotation.value());

    Runners annotation2 = proxyClass.getAnnotation(Runners.class);
    Assert.assertNotNull(annotation2);
    Assert.assertEquals(BlockJUnit4ClassRunner.class, annotation2.value());
    Assert.assertArrayEquals(new Class[] {AnotherTestRunner.class, TestRunner.class}, annotation2.others());
}
 
Example 30
Project: sosiefier   File: AnnotatedBuilder.java   View source code 5 votes vote down vote up
@Override
public Runner runnerForClass(Class<?> testClass) throws Exception {
    for (Class<?> currentTestClass = testClass; currentTestClass != null;
         currentTestClass = getEnclosingClassForNonStaticMemberClass(currentTestClass)) {
        RunWith annotation = currentTestClass.getAnnotation(RunWith.class);
        if (annotation != null) {
            return buildRunner(annotation.value(), testClass);
        }
    }

    return null;
}
 
Example 31
Project: contiperf   File: AbstractContiPerfTest.java   View source code 5 votes vote down vote up
protected void runTest(Class<?> testClass) throws Exception {
RunWith runWith = testClass.getAnnotation(RunWith.class);
if (runWith != null) {
    runAnnotatedTestClass(testClass, runWith);
} else {
    runPlainTestClass(testClass);
}
   }
 
Example 32
Project: contiperf   File: AbstractContiPerfTest.java   View source code 5 votes vote down vote up
private void runAnnotatedTestClass(Class<?> testClass, RunWith runWith)
    throws Exception {
Class<? extends Runner> runnerClass = runWith.value();
Constructor<? extends Runner> constructor = runnerClass
	.getConstructor(Class.class);
Runner runner = constructor.newInstance(testClass);
RunNotifier notifier = new RunNotifier();
notifier.addListener(new MyListener());
runner.run(notifier);
   }
 
Example 33
Project: pitest   File: JUnit4SuiteFinder.java   View source code 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 34
Project: lcm   File: AnnotatedBuilder.java   View source code 5 votes vote down vote up
@Override
public Runner runnerForClass(Class<?> testClass) throws Exception {
    RunWith annotation = testClass.getAnnotation(RunWith.class);
    if (annotation != null) {
        return buildRunner(annotation.value(), testClass);
    }
    return null;
}
 
Example 35
Project: tools-idea   File: TestRunnerUtil.java   View source code 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 36
Project: junit-converter   File: SuiteAnnotationsImportingStage.java   View source code 5 votes vote down vote up
/**
 * @see junitconverter.stages.TestConversionStage#convertClass(junitconverter.testcase.TestCaseClass)
 */
public void convertClass(TestCaseClass testCase)
{
	codeEditor.importClass(testCase, Suite.class);
	codeEditor.importClass(testCase, RunWith.class);
	codeEditor.importClass(testCase, SuiteClasses.class); // FIXME Doesn't import it properly. Adds a $ instead of . between SUite and SuiteClasses
}
 
Example 37
Project: jbehave-core   File: AnnotatedEmbedderUtils.java   View source code 5 votes vote down vote up
private static Class<?> runnerClass(String annotatedClassName, EmbedderClassLoader classLoader) {
    Class<?> annotatedClass = loadClass(annotatedClassName, classLoader);
    RunWith annotation = annotatedClass.getAnnotation(RunWith.class);
    if (annotation != null) {
        return annotation.value();
    }
    throw new MissingAnnotatedEmbedderRunner(annotatedClass);
}
 
Example 38
Project: buck   File: JUnitRunner.java   View source code 5 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;
  }
  // 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 39
Project: consulo   File: TestRunnerUtil.java   View source code 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 40
Project: junit   File: AnnotatedBuilder.java   View source code 5 votes vote down vote up
@Override
public Runner runnerForClass(Class<?> testClass) throws Exception {
    RunWith annotation = testClass.getAnnotation(RunWith.class);
    if (annotation != null) {
        return buildRunner(annotation.value(), testClass);
    }
    return null;
}