@Override public Runner runnerForClass(Class<?> testClass) throws Throwable { try { return new BlockJUnit4ClassRunner(testClass); } catch (Throwable t) { //failed to instantiate BlockJUnitRunner. try deprecated JUnitRunner (for JUnit < 4.5) try { Class<Runner> runnerClass = (Class<Runner>) Thread.currentThread().getContextClassLoader().loadClass("org.junit.internal.runners.JUnit4ClassRunner"); final Constructor<Runner> constructor = runnerClass.getConstructor(Class.class); return constructor.newInstance(testClass); } catch (Throwable e) { LoggerFactory.getLogger(getClass()).warn("Unable to load JUnit4 runner to calculate Ignored test cases", e); } } return null; }
protected static List<TestRequest> getTestRequests(String folderName, Filter filter) { List<TestRequest> requests = new ArrayList<>(); getTestClasses(folderName).forEach(testClass -> { try { new BlockJUnit4ClassRunner(testClass).getDescription().getChildren() .forEach(description -> { if (filter.shouldRun(description)) { TestRequest request = new TestRequest(description); request.setTestRunUUID(TestUUID.getTestUUID()); requests.add(request); } }); } catch (InitializationError e) { LOGGER.log(e); } }); return requests; }
public TestResults runTest(final Class<?> testClazz, final String methodName) throws InitializationError { BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(testClazz) { @Override protected List<FrameworkMethod> computeTestMethods() { try { Method method = testClazz.getMethod(methodName); return Arrays.asList(new FrameworkMethod(method)); } catch (Exception e) { throw new RuntimeException(e); } } }; TestResults res = new TestResults(logger, server, playerName); runner.run(res); return res; }
@Test public void testClassWithPersistenceContextWithKonfiguredUnitNameSpecified() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule"); ruleField.annotate(Rule.class); final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()")); ruleField.init(instance); final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em"); final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class); jAnnotation.param("unitName", "test-unit-1"); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(cut); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class); verify(listener).testStarted(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); verify(listener).testFinished(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); }
@Test public void describeChildCreatesDescriptionForWithTestUserTest() throws Exception { SpringSecurityJUnit4ClassRunner runner = new SpringSecurityJUnit4ClassRunner(MockWithMockUserTest.class); Method method2Test = MockWithMockUserTest.class.getMethod("testWithWithMockUser"); FrameworkMethod method = new AnnotationFrameworkMethod(new FrameworkMethod(method2Test), method2Test.getDeclaredAnnotation(WithMockUser.class)); Description actualDescription = runner.describeChild(method); BlockJUnit4ClassRunner expectedRunner = new BlockJUnit4ClassRunner(MockWithMockUserTest.class); Method method1 = BlockJUnit4ClassRunner.class.getDeclaredMethod("describeChild", FrameworkMethod.class); method1.setAccessible(true); Description expectedDescription = (Description) method1.invoke(expectedRunner, method); assertDescriptionDetailsEqual(expectedDescription, actualDescription); assertEquals(expectedDescription.getChildren().size(), actualDescription.getChildren().size()); }
@Test public void useChildHarvester() throws InitializationError { log = ""; ParentRunner<?> runner = new BlockJUnit4ClassRunner(FruitTest.class); runner.setScheduler(new RunnerScheduler() { public void schedule(Runnable childStatement) { log += "before "; childStatement.run(); log += "after "; } public void finished() { log += "afterAll "; } }); runner.run(new RunNotifier()); assertEquals("before apple after before banana after afterAll ", log); }
@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(); }
@Override protected List<Runner> getChildren() { // one runner for each parameter List<Runner> runners = super.getChildren(); List<Runner> proxyRunners = new ArrayList<>(runners.size()); for (Runner runner : runners) { // if the next line fails then the internal of Parameterized.class has been updated since this works with JUnit 4.11 BlockJUnit4ClassRunner blockJUnit4ClassRunner = (BlockJUnit4ClassRunner) runner; Description description = blockJUnit4ClassRunner.getDescription(); String name = description.getDisplayName(); try { proxyRunners .add(new ProxyTestClassRunnerForParameters(mTestClass, mContainerUrl, name)); } catch (InitializationError e) { throw new RuntimeException("Could not create runner for paramamter " + name, e); } } return proxyRunners; }
protected List getChildren() { final List children = super.getChildren(); for (int i = 0; i < children.size(); i++) { try { final BlockJUnit4ClassRunner child = (BlockJUnit4ClassRunner)children.get(i); final Method getChildrenMethod = BlockJUnit4ClassRunner.class.getDeclaredMethod("getChildren", new Class[0]); getChildrenMethod.setAccessible(true); final List list = (List)getChildrenMethod.invoke(child, new Object[0]); for (Iterator iterator = list.iterator(); iterator.hasNext(); ) { final FrameworkMethod description = (FrameworkMethod)iterator.next(); if (!description.getName().equals(myMethodName)) { iterator.remove(); } } } catch (Exception e) { e.printStackTrace(); } } return children; }
public EjbWithMockitoRunner(Class<?> klass) throws InvocationTargetException, InitializationError { runner = new BlockJUnit4ClassRunner(klass) { @Override protected Object createTest() throws Exception { Object test = super.createTest(); // init annotated mocks before tests MockitoAnnotations.initMocks(test); // inject annotated EJBs before tests injectEjbs(test); // Rollback any existing transaction before starting a new one TransactionUtils.rollbackTransaction(); TransactionUtils.endTransaction(true); // Start a new transaction TransactionUtils.beginTransaction(); return test; } }; }
public TestResult handleRequest(TestRequest testRequest, Context context) { LoggerContainer.LOGGER = new Logger(context.getLogger()); System.setProperty("target.test.uuid", testRequest.getTestRunUUID()); Optional<Result> result = Optional.empty(); try { BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(getTestClass(testRequest)); runner.filter(new MethodFilter(testRequest.getFrameworkMethod())); result = ofNullable(new JUnitCore().run(runner)); } catch (Exception e) { testResult.setThrowable(e); LOGGER.log(e); } if (result.isPresent()) { testResult.setRunCount(result.get().getRunCount()); testResult.setRunTime(result.get().getRunTime()); LOGGER.log("Run count: " + result.get().getRunCount()); result.get().getFailures().forEach(failure -> { LOGGER.log(failure.getException()); testResult.setThrowable(failure.getException()); }); } return testResult; }
private void createSuite(Class<?> suiteClass) throws Exception { suite = new XTFTestSuite(suiteClass, new RunnerBuilder() { @Override public Runner runnerForClass(Class<?> testClass) throws Throwable { return new BlockJUnit4ClassRunner(testClass); } }); }
static void runChildBefore(final BlockJUnit4ClassRunner runner, final FrameworkMethod method, final RunNotifier notifier) { final StroomExpectedException stroomExpectedException = method.getAnnotation(StroomExpectedException.class); if (stroomExpectedException != null) { StroomJunitConsoleAppender.setExpectedException(stroomExpectedException.exception()); LOGGER.info(">>> %s. Expecting Exceptions %s", method.getMethod(), stroomExpectedException.exception()); } else { LOGGER.info(">>> %s", method.getMethod()); } }
static void runChildAfter(final BlockJUnit4ClassRunner runner, final FrameworkMethod method, final RunNotifier notifier, final LogExecutionTime logExecutionTime) { LOGGER.info("<<< %s took %s", method.getMethod(), logExecutionTime); if (StroomJunitConsoleAppender.getUnexpectedExceptions().size() > 0) { notifier.fireTestFailure(new Failure( Description.createTestDescription(runner.getTestClass().getJavaClass(), method.getName()), StroomJunitConsoleAppender.getUnexpectedExceptions().get(0))); } StroomJunitConsoleAppender.setExpectedException(null); }
@Override public Runner runnerForClass(Class<?> testClass) throws Throwable { return new BlockJUnit4ClassRunner(testClass) { public Object createTest() throws Exception { final Object obj = super.createTest(); injector.injectMembers(obj); return obj; } }; }
@Test public void testClassWithPersistenceUnitWithKonfiguredUnitNameSpecified() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule"); ruleField.annotate(Rule.class); final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()")); ruleField.init(instance); final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf"); final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.class); jAnnotation.param("unitName", "test-unit-1"); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(cut); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class); verify(listener).testStarted(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); verify(listener).testFinished(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); }
@Test public void describeChildMatchesBlockJUnit4ClassRunnerForNonWithTestUserTest() throws Exception { SpringSecurityJUnit4ClassRunner runner = new SpringSecurityJUnit4ClassRunner(MockWithMockUserTest.class); FrameworkMethod method = new FrameworkMethod(MockWithMockUserTest.class.getMethod("testWithoutWithMockUser")); Description actualDescription = runner.describeChild(method); BlockJUnit4ClassRunner expectedRunner = new BlockJUnit4ClassRunner(MockWithMockUserTest.class); Method method1 = BlockJUnit4ClassRunner.class.getDeclaredMethod("describeChild", FrameworkMethod.class); method1.setAccessible(true); Description expectedDescription = (Description) method1.invoke(expectedRunner, method); assertDescriptionDetailsEqual(expectedDescription, actualDescription); assertEquals(expectedDescription.getChildren().size(), actualDescription.getChildren().size()); }
@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()); }
public Runner runnerForClass(Class<?> testClass) throws Throwable { try { return new BlockJUnit4ClassRunner(testClass); } catch (Throwable t) { //failed to instantiate BlockJUnitRunner. try deprecated JUnitRunner (for JUnit < 4.5) try { Class<Runner> runnerClass = (Class<Runner>) Thread.currentThread().getContextClassLoader().loadClass("org.junit.internal.runners.JUnit4ClassRunner"); final Constructor<Runner> constructor = runnerClass.getConstructor(Class.class); return constructor.newInstance(testClass); } catch (Throwable e) { LoggerFactory.getLogger(getClass()).warn("Unable to load JUnit4 runner to calculate Ignored test cases", e); } } return null; }
@Test public void categoryFilterLeavesOnlyMatchingMethods() throws InitializationError, NoTestsRemainException { CategoryFilter filter = CategoryFilter.include(SlowTests.class); BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(A.class); filter.apply(runner); assertEquals(1, runner.testCount()); }
@Test public void categoryFilterRejectsIncompatibleCategory() throws InitializationError, NoTestsRemainException { CategoryFilter filter = CategoryFilter.include(SlowTests.class); BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner( OneFastOneSlow.class); filter.apply(runner); assertEquals(1, runner.testCount()); }
private List<Throwable> validateAllMethods(Class<?> clazz) { try { new BlockJUnit4ClassRunner(clazz); } catch (InitializationError e) { return e.getCauses(); } return Collections.emptyList(); }
@Test public void detectNonStaticEnclosedClass() throws Exception { try { new BlockJUnit4ClassRunner(OuterClass.Enclosed.class); } catch (InitializationError e) { List<Throwable> causes = e.getCauses(); assertEquals("Wrong number of causes.", 1, causes.size()); assertEquals( "Wrong exception.", "The inner class org.junit.tests.running.classes.BlockJUnit4ClassRunnerTest$OuterClass$Enclosed is not static.", causes.get(0).getMessage()); } }
private CountingRunListener runTestWithParentRunner(Class<?> testClass) throws InitializationError { CountingRunListener listener = new CountingRunListener(); RunNotifier runNotifier = new RunNotifier(); runNotifier.addListener(listener); ParentRunner runner = new BlockJUnit4ClassRunner(testClass); runner.run(runNotifier); return listener; }
public JFixtureJUnitRunner(Class<?> clazz) throws InitializationError { this.runner = new BlockJUnit4ClassRunner(clazz) { protected Statement withBefores(FrameworkMethod method, Object target, Statement statement) { Statement base = super.withBefores(method, target, statement); return new JUnitJFixtureStatement(base, target, new JFixture()); } }; }
public JUnit45AndHigherRunnerImpl(Class<?> klass) throws InitializationError { runner = new BlockJUnit4ClassRunner(klass) { protected Statement withBefores(FrameworkMethod method, Object target, Statement statement) { // init annotated mocks before tests MockitoAnnotations.initMocks(target); return super.withBefores(method, target, statement); } }; }
/** * Gets the PerformanceJUnitStatement for the test execution of the given method. * * @param currentMethod * Method that should be tested * @return PerformanceJUnitStatement for testing the method * @throws NoSuchMethodException * Thrown if the method does not exist * @throws SecurityException * Thrown if the method is not accessible * @throws IllegalAccessException * Thrown if the method is not accessible * @throws IllegalArgumentException * Thrown if the method has arguments * @throws InvocationTargetException * Thrown if the method is not accessible */ private PerformanceJUnitStatement getStatement(final FrameworkMethod currentMethod) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { try { final Object testObject = new ReflectiveCallable() { @Override protected Object runReflectiveCall() throws Throwable { return createTest(); } }.run(); if (classFinished){ return null; } LOG.debug("Statement: " + currentMethod.getName() + " " + classFinished); Statement testExceptionTimeoutStatement = methodInvoker(currentMethod, testObject); testExceptionTimeoutStatement = possiblyExpectingExceptions(currentMethod, testObject, testExceptionTimeoutStatement); // testExceptionTimeoutStatement = withPotentialTimeout(currentMethod, test, testExceptionTimeoutStatement); final Method withRulesMethod = BlockJUnit4ClassRunner.class.getDeclaredMethod("withRules", FrameworkMethod.class, Object.class, Statement.class); withRulesMethod.setAccessible(true); final Statement withRuleStatement = (Statement) withRulesMethod.invoke(this, new Object[] { currentMethod, testObject, testExceptionTimeoutStatement }); final PerformanceJUnitStatement perfStatement = new PerformanceJUnitStatement(withRuleStatement, testObject); final List<FrameworkMethod> befores = getTestClass().getAnnotatedMethods(Before.class); final List<FrameworkMethod> afters = getTestClass().getAnnotatedMethods(After.class); perfStatement.setBefores(befores); perfStatement.setAfters(afters); return perfStatement; } catch (final Throwable e) { return new PerformanceFail(e); } }
public JExUnit(Class<?> clazz) throws Throwable { super(clazz, Collections.<Runner>emptyList()); ServiceRegistry.initialize(); DataProvider dataprovider = null; List<DataProvider> dataproviders = ServiceRegistry.getInstance().getServicesFor(DataProvider.class); if (dataproviders != null) { for (DataProvider dp : dataproviders) { if (dp.canProvide(clazz)) { dataprovider = dp; } } } if (dataprovider == null) { throw new IllegalArgumentException(); } TestContextManager.add(DataProvider.class, dataprovider); dataprovider.initialize(clazz); // add the Parameterized JExUnitBase, initialized with the ExcelFileName for (int i = 0; i < dataprovider.numberOfTests(); i++) { runners.add(new Parameterized(JExUnitBase.class, clazz, i, dataprovider.getIdentifier(i))); } // if there are Test-methods defined in the test-class, this once will be execute too try { runners.add(new BlockJUnit4ClassRunner(clazz)); } catch (Exception e) { // ignore (if there is no method annotated with @Test in the class, an exception is // thrown -> so we can ignore this here) LOG.finer("No method found annotated with @Test; this will be ignored!"); } }
@Override protected List<Runner> getChildren() { for (Runner runner : super.getChildren()) { BlockJUnit4ClassRunner classRunner = (BlockJUnit4ClassRunner) runner; classRunner.setScheduler(scheduler); } return super.getChildren(); }