Java Code Examples for org.junit.runner.notification.RunNotifier#addListener()

The following examples show how to use org.junit.runner.notification.RunNotifier#addListener() . 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: RunUntilFailure.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private void runRepeatedly(Statement statement, Description description,  
        RunNotifier notifier) {
    notifier.addListener(new RunListener() {
        @Override
        public void testFailure(Failure failure) {
            hasFailure = true;
        }
    });
    for (Description desc : description.getChildren()) {  
        if (hasFailure) {
            notifier.fireTestIgnored(desc);
        } else if(!desc.isSuite()) {
            runLeaf(statement, desc, notifier);
        }
    }  
}
 
Example 2
Source File: JUnitTestingUtils.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Run the tests in the supplied {@code testClass}, using the specified
 * {@link Runner}, and assert the expectations of the test execution.
 *
 * <p>If the specified {@code runnerClass} is {@code null}, the tests
 * will be run with the runner that the test class is configured with
 * (i.e., via {@link RunWith @RunWith}) or the default JUnit runner.
 *
 * @param runnerClass the explicit runner class to use or {@code null}
 * if the implicit runner should be used
 * @param testClass the test class to run with JUnit
 * @param expectedStartedCount the expected number of tests that started
 * @param expectedFailedCount the expected number of tests that failed
 * @param expectedFinishedCount the expected number of tests that finished
 * @param expectedIgnoredCount the expected number of tests that were ignored
 * @param expectedAssumptionFailedCount the expected number of tests that
 * resulted in a failed assumption
 */
public static void runTestsAndAssertCounters(Class<? extends Runner> runnerClass, Class<?> testClass,
		int expectedStartedCount, int expectedFailedCount, int expectedFinishedCount, int expectedIgnoredCount,
		int expectedAssumptionFailedCount) throws Exception {

	TrackingRunListener listener = new TrackingRunListener();

	if (runnerClass != null) {
		Constructor<?> constructor = runnerClass.getConstructor(Class.class);
		Runner runner = (Runner) BeanUtils.instantiateClass(constructor, testClass);
		RunNotifier notifier = new RunNotifier();
		notifier.addListener(listener);
		runner.run(notifier);
	}
	else {
		JUnitCore junit = new JUnitCore();
		junit.addListener(listener);
		junit.run(testClass);
	}

	assertEquals("tests started for [" + testClass + "]:", expectedStartedCount, listener.getTestStartedCount());
	assertEquals("tests failed for [" + testClass + "]:", expectedFailedCount, listener.getTestFailureCount());
	assertEquals("tests finished for [" + testClass + "]:", expectedFinishedCount, listener.getTestFinishedCount());
	assertEquals("tests ignored for [" + testClass + "]:", expectedIgnoredCount, listener.getTestIgnoredCount());
	assertEquals("failed assumptions for [" + testClass + "]:", expectedAssumptionFailedCount, listener.getTestAssumptionFailureCount());
}
 
Example 3
Source File: WebTesterJUnitRunnerTest.java    From webtester2-core with Apache License 2.0 6 votes vote down vote up
private static void executeTestClass(Class<?> testClass) throws Throwable {

        Throwable[] throwables = new Throwable[1];
        WebTesterJUnitRunner runner = new WebTesterJUnitRunner(testClass);
        RunNotifier notifier = new RunNotifier();
        notifier.addListener(new RunListener() {

            public void testFailure(Failure failure) throws Exception {
                System.out.println("testFailure");
                throwables[0] = failure.getException();
            }

        });
        runner.run(notifier);

        if (throwables[0] != null) {
            throw throwables[0];
        }

    }
 
Example 4
Source File: ConsoleSpammingMockitoJUnitRunner.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run(RunNotifier notifier) {
    RunListener listener = new RunListener() {
        WarningsCollector warningsCollector;
        
        @Override
        public void testStarted(Description description) throws Exception {
            warningsCollector = new WarningsCollector();
        }
        
        @Override public void testFailure(Failure failure) throws Exception {                
            logger.log(warningsCollector.getWarnings());
        }
    };

    notifier.addListener(listener);

    runner.run(notifier);
}
 
Example 5
Source File: ConsoleSpammingMockitoJUnitRunner.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run(RunNotifier notifier) {
    RunListener listener = new RunListener() {
        WarningsCollector warningsCollector;
        
        @Override
        public void testStarted(Description description) throws Exception {
            warningsCollector = new WarningsCollector();
        }
        
        @Override public void testFailure(Failure failure) throws Exception {                
            logger.log(warningsCollector.getWarnings());
        }
    };

    notifier.addListener(listener);

    runner.run(notifier);
}
 
Example 6
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 7
Source File: CdiTestRunner.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private static synchronized void addLogRunListener(RunNotifier notifier, int identityHashCode)
{
    if (notifierIdentities.contains(identityHashCode))
    {
        return;
    }
    notifierIdentities.add(identityHashCode);
    notifier.addListener(new CdiTestSuiteRunner.LogRunListener());
}
 
Example 8
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 9
Source File: ZeroCodePackageRunner.java    From zerocode with Apache License 2.0 5 votes vote down vote up
@Override
public void run(RunNotifier notifier) {
    ZeroCodeTestReportListener reportListener = new ZeroCodeTestReportListener(smartUtils.getMapper(), getInjectedReportGenerator());
    notifier.addListener(reportListener);

    LOGGER.info("System property " + ZEROCODE_JUNIT + "=" + getProperty(ZEROCODE_JUNIT));
    if (!CHARTS_AND_CSV.equals(getProperty(ZEROCODE_JUNIT))) {
        notifier.addListener(reportListener);
    }

    super.run(notifier);

    handleNoRunListenerReport(reportListener);
}
 
Example 10
Source File: JUnitTestingUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Run the tests in the supplied {@code testClass}, using the specified
 * {@link Runner}, and assert the expectations of the test execution.
 *
 * <p>If the specified {@code runnerClass} is {@code null}, the tests
 * will be run with the runner that the test class is configured with
 * (i.e., via {@link RunWith @RunWith}) or the default JUnit runner.
 *
 * @param runnerClass the explicit runner class to use or {@code null}
 * if the default JUnit runner should be used
 * @param testClass the test class to run with JUnit
 * @param expectedStartedCount the expected number of tests that started
 * @param expectedFailedCount the expected number of tests that failed
 * @param expectedFinishedCount the expected number of tests that finished
 * @param expectedIgnoredCount the expected number of tests that were ignored
 * @param expectedAssumptionFailedCount the expected number of tests that
 * resulted in a failed assumption
 */
public static void runTestsAndAssertCounters(Class<? extends Runner> runnerClass, Class<?> testClass,
		int expectedStartedCount, int expectedFailedCount, int expectedFinishedCount, int expectedIgnoredCount,
		int expectedAssumptionFailedCount) throws Exception {

	TrackingRunListener listener = new TrackingRunListener();

	if (runnerClass != null) {
		Constructor<?> constructor = runnerClass.getConstructor(Class.class);
		Runner runner = (Runner) BeanUtils.instantiateClass(constructor, testClass);
		RunNotifier notifier = new RunNotifier();
		notifier.addListener(listener);
		runner.run(notifier);
	}
	else {
		JUnitCore junit = new JUnitCore();
		junit.addListener(listener);
		junit.run(testClass);
	}

	// @formatter:off
	assertAll(
		() -> assertEquals(expectedStartedCount, listener.getTestStartedCount(), "tests started for [" + testClass + "]"),
		() -> assertEquals(expectedFailedCount, listener.getTestFailureCount(), "tests failed for [" + testClass + "]"),
		() -> assertEquals(expectedFinishedCount, listener.getTestFinishedCount(), "tests finished for [" + testClass + "]"),
		() -> assertEquals(expectedIgnoredCount, listener.getTestIgnoredCount(), "tests ignored for [" + testClass + "]"),
		() -> assertEquals(expectedAssumptionFailedCount, listener.getTestAssumptionFailureCount(), "failed assumptions for [" + testClass + "]")
	);
	// @formatter:on
}
 
Example 11
Source File: SpectrumHelper.java    From spectrum with MIT License 5 votes vote down vote up
/**
 * Allows a listener to listen to a run.
 * @param specClass the class to execute via Spectrum
 * @param listener the listener to use
 * @param <T> type of listener
 * @return the listener for fluent usage
 * @throws Exception on error
 */
public static <T extends RunListener> T runWithListener(final Class<?> specClass,
    final T listener) throws Exception {
  RunNotifier notifier = new RunNotifier();
  notifier.addListener(listener);
  new Spectrum(specClass).run(notifier);

  return listener;
}
 
Example 12
Source File: ArkBootRunner.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
@Override
public void run(RunNotifier notifier) {
    ClassLoader oldClassLoader = ClassLoaderUtils.pushContextClassLoader(DelegateArkContainer
        .getTestClassLoader());
    try {
        notifier.addListener(JUnitExecutionListener.getRunListener());
        runner.run(notifier);
    } finally {
        ClassLoaderUtils.popContextClassLoader(oldClassLoader);
    }
}
 
Example 13
Source File: JUnitTestClassExecuter.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void runTestClass(String testClassName) throws ClassNotFoundException {
    final Class<?> testClass = Class.forName(testClassName, true, applicationClassLoader);
    Request request = Request.aClass(testClass);
    if (options.hasCategoryConfiguration()) {
        Transformer<Class<?>, String> transformer = new Transformer<Class<?>, String>() {
            public Class<?> transform(final String original) {
                try {
                    return applicationClassLoader.loadClass(original);
                } catch (ClassNotFoundException e) {
                    throw new InvalidUserDataException(String.format("Can't load category class [%s].", original), e);
                }
            }
        };
        request = request.filterWith(new CategoryFilter(
                CollectionUtils.collect(options.getIncludeCategories(), transformer),
                CollectionUtils.collect(options.getExcludeCategories(), transformer)
        ));
    }

    if (!options.getIncludedTests().isEmpty()) {
        request = request.filterWith(new MethodNameFilter(options.getIncludedTests()));
    }

    Runner runner = request.getRunner();
    //In case of no matching methods junit will return a ErrorReportingRunner for org.junit.runner.manipulation.Filter.class.
    //Will be fixed with adding class filters
    if (!org.junit.runner.manipulation.Filter.class.getName().equals(runner.getDescription().getDisplayName())) {
        RunNotifier notifier = new RunNotifier();
        notifier.addListener(listener);
        runner.run(notifier);
    }
}
 
Example 14
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 15
Source File: WildflyTestRunner.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void run(final RunNotifier notifier) {
    notifier.addListener(new RunListener() {
        @Override
        public void testRunFinished(Result result) throws Exception {
            super.testRunFinished(result);
            parameterDescriptions.clear();
            if (automaticServerControl) {
                controller.stop();
            }
        }
    });
    configureTestRun();
    if (!serverSetupTasks.isEmpty() && !automaticServerControl) {
        throw new RuntimeException("Can't run setup tasks with manual server control");
    }
    boolean providerInstalled = false;
    if (Security.getProvider(ELYTRON_PROVIDER.getName()) == null) {
        Security.insertProviderAt(ELYTRON_PROVIDER, 0);
        providerInstalled = true;
    }
    if (automaticServerControl) {
        runSetupTasks();
    }
    super.run(notifier);
    if (automaticServerControl) {
        runTearDownTasks();
    }
    if (providerInstalled) {
        Security.removeProvider(ELYTRON_PROVIDER.getName());
    }
}
 
Example 16
Source File: XpectConfigurationDelegate.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Runs provided File in Engine. Returns output of execution.
 */
public void execute(ILaunch launch, XpectRunConfiguration runConfiguration) throws RuntimeException {

	Job job = new Job(launch.getLaunchConfiguration().getName()) {

		@Override
		protected IStatus run(IProgressMonitor monitor) {
			XpectRunner xr;
			try {
				xr = new XpectRunner(N4IDEXpectTestClass.class);
			} catch (InitializationError e) {
				N4IDEXpectUIPlugin.logError("cannot initialize xpect runner", e);
				return Status.CANCEL_STATUS;
			}

			// TODO support multiple selection
			/*
			 * if Project provided, or package files should be discovered there. Also multiple selected files
			 */
			String testFileLocation = runConfiguration.getXtFileToRun();

			IXpectURIProvider uriprov = xr.getUriProvider();
			if (uriprov instanceof N4IDEXpectTestURIProvider) {
				((N4IDEXpectTestURIProvider) uriprov).addTestFileLocation(testFileLocation);
			}

			Result result = new Result();
			RunNotifier notifier = new RunNotifier();
			RunListener listener = result.createListener();
			N4IDEXpectRunListener n4Listener = new N4IDEXpectRunListener();

			notifier.addFirstListener(listener);
			notifier.addListener(n4Listener);

			try {
				notifier.fireTestRunStarted(xr.getDescription());
				xr.run(notifier);
				notifier.fireTestRunFinished(result);
			} finally {
				notifier.removeListener(n4Listener);
				notifier.removeListener(listener);
			}
			// Do something with test run result?
			// return result;

			return Status.OK_STATUS;
		}

	};
	job.setUser(true);
	job.schedule();
}
 
Example 17
Source File: JUnit44RunnerImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public void run(RunNotifier notifier) {
    // add listener that validates framework usage at the end of each test
    notifier.addListener(new FrameworkUsageValidator(notifier));

    runner.run(notifier);
}
 
Example 18
Source File: JUnit45AndHigherRunnerImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public void run(final RunNotifier notifier) {
    // add listener that validates framework usage at the end of each test
    notifier.addListener(new FrameworkUsageValidator(notifier));

    runner.run(notifier);
}
 
Example 19
Source File: DebugSuite.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void run(RunNotifier runNotifier) {
    runNotifier.addListener(new DebugListener());
    super.run(runNotifier);
}
 
Example 20
Source File: JUnitGradeSheetTestRunner.java    From public with Apache License 2.0 3 votes vote down vote up
@Override
public void run(final RunNotifier notifier) {
    listener.testRunStarted(getDescription());

    notifier.addListener(listener);

    super.run(notifier);

    notifier.removeListener(listener);

    listener.testRunFinished(null);
}