@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); }
/** * @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; }
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(); }
/** * @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; }
@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; }
@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(); }
/** * @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$ }
@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(); } }
@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; }
@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); }
@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]); }
@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(); }
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; }
@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; }
@Test public void testClassWithoutPersistenceContextField() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class); jAnnotationUse.param("value", JpaUnitRunner.class); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); final JpaUnitRunner runner = new JpaUnitRunner(cut); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class); verify(listener).testFailure(failureCaptor.capture()); final Failure failure = failureCaptor.getValue(); assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class)); assertThat(failure.getException().getMessage(), containsString("EntityManagerFactory or EntityManager field annotated")); }
@Test public void testClassWithMultiplePersistenceUnitFields() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class); jAnnotationUse.param("value", JpaUnitRunner.class); final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf1"); emf1Field.annotate(PersistenceUnit.class); final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf2"); emf2Field.annotate(PersistenceUnit.class); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); final JpaUnitRunner runner = new JpaUnitRunner(cut); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class); verify(listener).testFailure(failureCaptor.capture()); final Failure failure = failureCaptor.getValue(); assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class)); assertThat(failure.getException().getMessage(), containsString("Only single field is allowed")); }
@Test public void testClassWithPersistenceContextAndPersistenceUnitFields() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class); jAnnotationUse.param("value", JpaUnitRunner.class); final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em"); emf1Field.annotate(PersistenceContext.class); final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf"); emf2Field.annotate(PersistenceUnit.class); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); final JpaUnitRunner runner = new JpaUnitRunner(cut); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class); verify(listener).testFailure(failureCaptor.capture()); final Failure failure = failureCaptor.getValue(); assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class)); assertThat(failure.getException().getMessage(), containsString("either @PersistenceUnit or @PersistenceContext")); }
@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")); }
@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")); }
@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")); }
@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")); }
@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")); }
@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")); }
@Test public void testJpaUnitRunnerAndJpaUnitRuleFieldExcludeEachOther() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class); jAnnotationUse.param("value", JpaUnitRunner.class); final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf"); final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.class); jAnnotation.param("unitName", "test-unit-1"); final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule"); ruleField.annotate(Rule.class); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); try { // WHEN new JpaUnitRunner(cut); fail("InitializationError expected"); } catch (final InitializationError e) { // expected assertThat(e.getCauses().get(0).getMessage(), containsString("exclude each other")); } }
private TypeSpec classTest(ClassName className, List<MethodSpec> methodSpecs) { String methodName = Introspector .decapitalize(className.simpleName()); MethodSpec abstractMethodInstanceToTest = methodBuilder(methodName) .addModifiers(Modifier.ABSTRACT, Modifier.PROTECTED) .returns(className) .build(); FieldSpec exception = FieldSpec.builder(ExpectedException.class, "exception") .addAnnotation(Rule.class) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .initializer("$T.none()", ExpectedException.class) .build(); return TypeSpec.classBuilder(className.simpleName() + "Test_") .addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC) .addMethod(abstractMethodInstanceToTest) .addField(exception) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", MockeryProcessor.class.getCanonicalName()) .addMember("comments", "$S", CMessages.codeGenerateWarning()) .build()) .addAnnotation(AnnotationSpec.builder(RunWith.class) .addMember("value", "$T.class", OrderedRunner.class) .build()) .addMethods(methodSpecs) .build(); }
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()); }
@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; }
@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()); }
@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; }
protected void runTest(Class<?> testClass) throws Exception { RunWith runWith = testClass.getAnnotation(RunWith.class); if (runWith != null) { runAnnotatedTestClass(testClass, runWith); } else { runPlainTestClass(testClass); } }
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); }
private boolean hasSuitableRunnner(final Class<?> clazz) { final RunWith runWith = clazz.getAnnotation(RunWith.class); if (runWith != null) { return (runWith.value().equals(Suite.class)); } return false; }
@Override public Runner runnerForClass(Class<?> testClass) throws Exception { RunWith annotation = testClass.getAnnotation(RunWith.class); if (annotation != null) { return buildRunner(annotation.value(), testClass); } return null; }
/** * @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 }
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); }
/** 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; }