Java 类org.junit.runner.Description 实例源码

项目:adyen-android    文件:RetryTest.java   
private Statement statement(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            Throwable caughtThrowable = null;
            for (int i = 0; i < retryCount; i++) {
                try {
                    base.evaluate();
                    return;
                } catch (Throwable t) {
                    caughtThrowable = t;
                    System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed");
                }
            }
            System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures");
            throw caughtThrowable;
        }
    };
}
项目:Runnest    文件:EspressoTest.java   
private Statement statement(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            Throwable caughtThrowable = null;
            for (int i = 0; i < retryCount; i++) {
                try {
                    base.evaluate();
                    return;
                } catch (Throwable t) {
                    caughtThrowable = t;
                    System.err.println(description.getDisplayName() + ": run " + (i+1) + " failed");
                }
            }
            System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures");
            throw caughtThrowable;
        }
    };
}
项目:RIBs    文件:AndroidSchedulersRule.java   
@Override
protected void starting(Description description) {
  if (restoreHandlers) {
    // https://github.com/ReactiveX/RxAndroid/pull/358
    //            originalInitMainThreadInitHandler =
    // RxAndroidPlugins.getInitMainThreadScheduler();
    //            originalMainThreadHandler = RxAndroidPlugins.getMainThreadScheduler();
  }
  RxAndroidPlugins.reset();
  RxAndroidPlugins.setInitMainThreadSchedulerHandler(
      new Function<Callable<Scheduler>, Scheduler>() {
        @Override
        public Scheduler apply(Callable<Scheduler> schedulerCallable) throws Exception {
          return delegatingMainThreadScheduler;
        }
      });
  RxAndroidPlugins.setMainThreadSchedulerHandler(
      new Function<Scheduler, Scheduler>() {
        @Override
        public Scheduler apply(Scheduler scheduler) throws Exception {
          return delegatingMainThreadScheduler;
        }
      });
}
项目:GitHub    文件:InstallUncaughtExceptionHandlerListener.java   
@Override public void testRunStarted(Description description) throws Exception {
  System.err.println("Installing aggressive uncaught exception handler");
  oldDefaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
  Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override public void uncaughtException(Thread thread, Throwable throwable) {
      StringWriter errorText = new StringWriter(256);
      errorText.append("Uncaught exception in OkHttp thread \"");
      errorText.append(thread.getName());
      errorText.append("\"\n");
      throwable.printStackTrace(new PrintWriter(errorText));
      errorText.append("\n");
      if (lastTestStarted != null) {
        errorText.append("Last test to start was: ");
        errorText.append(lastTestStarted.getDisplayName());
        errorText.append("\n");
      }
      System.err.print(errorText.toString());
      System.exit(-1);
    }
  });
}
项目:io-comparison    文件:PrintEntrance.java   
@Override
public Statement apply(final Statement statement, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            long startTime = System.currentTimeMillis();
            try {
                if (printPre) {
                    System.out.println("Enter -->> " + description.getTestClass() + "#" + description.getMethodName());
                }
                statement.evaluate();
            } finally {
                if (printPost) {
                    long finishTime = System.currentTimeMillis() - startTime;
                    System.out.println("Leave -->> " + description.getMethodName() + ", elapsed(ms): " + finishTime);
                }
            }
        }
    };
}
项目:reactive-playing    文件:WordServiceWithRuleTest.java   
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            RxJavaPlugins.setIoSchedulerHandler(scheduler ->
                    Schedulers.trampoline());
            RxJavaPlugins.setComputationSchedulerHandler(scheduler ->
                    Schedulers.trampoline());
            RxJavaPlugins.setNewThreadSchedulerHandler(scheduler ->
                    Schedulers.trampoline());
            try {
                base.evaluate();
            } finally {
                RxJavaPlugins.reset();
            }
        }
    };
}
项目:GitHub    文件:MockWebServerTest.java   
@Test public void statementStartsAndStops() throws Throwable {
  final AtomicBoolean called = new AtomicBoolean();
  Statement statement = server.apply(new Statement() {
    @Override public void evaluate() throws Throwable {
      called.set(true);
      server.url("/").url().openConnection().connect();
    }
  }, Description.EMPTY);

  statement.evaluate();

  assertTrue(called.get());
  try {
    server.url("/").url().openConnection().connect();
    fail();
  } catch (ConnectException expected) {
  }
}
项目:GitHub    文件:RunWithRemoteService.java   
@Override
public Statement apply(final Statement base, Description description) {
    final RunTestWithRemoteService annotation = description.getAnnotation(RunTestWithRemoteService.class);
    if (annotation == null) {
        return base;
    }
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            before(annotation.remoteService());
            try {
                base.evaluate();
            } finally {
                if (!annotation.onLooperThread()) {
                    after();
                }
            }
        }
    };
}
项目:tablasco    文件:TableVerifier.java   
@Override
public final void starting(Description description)
{
    this.description = description;
    if (!this.isRebasing)
    {
        this.expectedResultsFuture = EXPECTED_RESULTS_LOADER_EXECUTOR.submit(new Callable<ExpectedResults>()
        {
            @Override
            public ExpectedResults call() throws Exception
            {
                return ExpectedResultsCache.getExpectedResults(expectedResultsLoader, getExpectedFile());
            }
        });
    }
    this.lifecycleEventHandler.onStarted(description);
}
项目:sling-org-apache-sling-testing-rules    文件:InstanceConfigRule.java   
public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            // save the instance config
            LOG.debug("Saving instance config {}", instanceConfig.getClass());
            instanceConfig.save();

            // Call any actions if any
            for (Action action : actions) {
                LOG.debug("Calling action {}", action.getClass());
                action.call();
            }

            // run the base statement
            LOG.debug("Running base statement");
            base.evaluate();

            if (withRestore) {
                LOG.debug("Restoring instance config {}", instanceConfig.getClass());
                instanceConfig.restore();
            }
        }
    };
}
项目:Architecture    文件:ImmediateSchedulersRule.java   
@Override
public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      RxJavaPlugins.reset();
      RxJavaPlugins.setIoSchedulerHandler(scheduler -> Schedulers.trampoline());
      RxJavaPlugins.setComputationSchedulerHandler(scheduler -> Schedulers.trampoline());
      RxJavaPlugins.setNewThreadSchedulerHandler(scheduler -> Schedulers.trampoline());

      try {
        base.evaluate();
      } finally {
        RxJavaPlugins.reset();
      }
    }
  };
}
项目:n4js    文件:N4IDEXpectRunListener.java   
/**
 * Called before any tests have been run.
 *
 * @param description
 *            describes the tests to be run
 */
@Override
public void testRunStarted(Description description) throws Exception {
    Display.getDefault().syncExec(new Runnable() {
        @Override
        public void run() {

            IWorkbenchWindow[] windows = N4IDEXpectUIPlugin.getDefault().getWorkbench().getWorkbenchWindows();
            try {
                N4IDEXpectView view = (N4IDEXpectView) windows[0].getActivePage().showView(
                        N4IDEXpectView.ID);
                view.notifySessionStarted(description);
            } catch (PartInitException e) {
                N4IDEXpectUIPlugin.logError("cannot refresh test view window", e);
            }
        }
    });
}
项目:n4js    文件:N4IDEXpectRunListener.java   
/**
 * Called when a test will not be run, generally because a test method is annotated with {@link org.junit.Ignore}.
 *
 * @param description
 *            describes the test that will not be run
 */
@Override
public void testIgnored(Description description) throws Exception {
    Display.getDefault().syncExec(new Runnable() {
        @Override
        public void run() {

            IWorkbenchWindow[] windows = N4IDEXpectUIPlugin.getDefault().getWorkbench().getWorkbenchWindows();
            try {
                N4IDEXpectView view = (N4IDEXpectView) windows[0].getActivePage().showView(
                        N4IDEXpectView.ID);
                view.notifyIgnoredExecutionOf(description);
            } catch (PartInitException e) {
                N4IDEXpectUIPlugin.logError("cannot refresh test view window", e);
            }
        }
    });
}
项目:willtest    文件:AbstractSeleniumProvider.java   
/**
 * Closes the webDriver which was created in this rule. Takes care if there is an exception while
 * closing the webDriver.
 */
@Override
protected void after(Description description, Throwable testFailure) throws Throwable {
    super.after(description, testFailure);
    if (getWebDriver() != null) {
        try {
            getWebDriver().quit();
        } catch (Exception ex) {
            if (!ex.getMessage().contains("It may have died")) {
                throw ex;
            }
            LOGGER.info("Error while closing browser. This error cannot be avoided somehow. " +
                    "This is not a big problem.", ex);
        }
        webDriver = null;
    }
}
项目:smart-testing    文件:SmartTestingSoftAssertions.java   
@Override
public Statement apply(Statement base, Description description) {
    return new Statement() {
        public void evaluate() throws Throwable {
            base.evaluate();
            assertAll();
        }
    };
}
项目:n4js    文件:XpectLabelProvider.java   
/** obtain {@link ImageDescriptor} for suite} */
private ImageDescriptor getSuiteImageDescriptor(Description desc, ExecutionStatus st) {
    ImageDescriptor descriptor;
    switch (st) {
    case PENDING:
        descriptor = getImageDescriptor("testsuite.png");
        break;
    case STARTED:
        descriptor = getImageDescriptor("testsuite_running.png");
        break;
    case IGNORED:
        descriptor = getImageDescriptor("testsuite_ignored.png");
        break;
    case PASSED:
        descriptor = getImageDescriptor("testsuite_pass.png");
        Optional<XpectFileContentAccess> fileContentAccess = XpectFileContentsUtil
                .getXpectFileContentAccess(desc);
        if (fileContentAccess.isPresent()) {
            if (fileContentAccess.get().containsFixme()) {
                descriptor = getImageDescriptor("testsuite_fixme.png");
            }
        }
        break;
    case FAILED:
        descriptor = getImageDescriptor("testsuite_fail.png");
        break;
    case ERROR:
        descriptor = getImageDescriptor("testsuite_error.png");
        break;

    default:
        descriptor = getImageDescriptor("n4_logo.png");
        break;
    }
    return descriptor;
}
项目:sling-org-apache-sling-testing-rules    文件:RunOnceRule.java   
@Override
public Statement apply(final Statement base, final Description description) {
    // if not done yet
    if (!RunOnceRule.run.getAndSet(true)) {
        LOG.debug("Applying {} once", rule.getClass());
        return rule.apply(base, description);
    } else {
        return base;
    }
}
项目:embedded-jms-junit    文件:EmbeddedJmsRuleImpl.java   
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            startService(getBrokerName(description));
            try {
                base.evaluate();
            } finally {
                stopService();
            }
        }
    };
}
项目:monarch    文件:RepeatRule.java   
protected void evaluate(final Statement statement, final Description description)
    throws Throwable {
  if (isTest(description)) {
    Repeat repeat = description.getAnnotation(Repeat.class);

    for (int count = 0, repetitions = getRepetitions(repeat); count < repetitions; count++) {
      statement.evaluate();
    }
  }
}
项目:tablasco    文件:TableVerifier.java   
@Override
public final void failed(Throwable e, Description description)
{
    if (!AssertionError.class.isInstance(e))
    {
        this.exceptionHandler.onException(this.getOutputFile(), e);
    }
    this.lifecycleEventHandler.onFailed(e, description);
}
项目:shabdiz    文件:ExperimentWatcher.java   
@Override
protected void failed(final Throwable e, final Description description) {

    super.failed(e, description);
    LOGGER.error("failed test {} due to error", description);
    LOGGER.error("failed test error", e);
}
项目:monarch    文件:RetryRule.java   
@Override
public Statement apply(final Statement base, final Description description) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      LocalRetryRule.this.evaluatePerTest(base, description);
    }
  };
}
项目:Rubus    文件:BenchmarkStatement.java   
public BenchmarkStatement(Statement base, Description description,
        IResultsConsumer[] consumers) {
    this.base = base;
    this.description = description;
    this.consumers = consumers;

    this.options = resolveOptions(description);
}
项目:spockito    文件:AbstractSpockitoTestRunner.java   
@Override
protected Description describeChild(final FrameworkMethod method) {
    final Spockito.Name name = Spockito.nameAnnotationOrNull(method.getMethod());
    if (name != null && name.shortFormat()) {
        return Description.createSuiteDescription(testName(method), method.getAnnotations());
    } else {
        return super.describeChild(method);
    }
}
项目:shabdiz    文件:ExperimentWatcher.java   
@Override
protected void skipped(final AssumptionViolatedException e, final Description description) {

    super.skipped(e, description);
    LOGGER.warn("skipped test {} due to assumption violation", description);
    LOGGER.warn("assumption violation", e);
}
项目:monarch    文件:RuleAndClassRuleTest.java   
@Override
public Statement apply(final Statement base, final Description description) {
  if (description.isTest()) {
    return statement(base);
  } else if (description.isSuite()) {
    return statementClass(base);
  }
  return base;
}
项目:allure-java    文件:AllureJunit4.java   
private <T extends Annotation> Stream<Label> getLabels(final Description result, final Class<T> labelAnnotation,
                                                       final Function<T, Label> extractor) {

    final List<Label> labels = getAnnotationsOnMethod(result, labelAnnotation).stream()
            .map(extractor)
            .collect(Collectors.toList());

    if (labelAnnotation.isAnnotationPresent(Repeatable.class) || labels.isEmpty()) {
        final Stream<Label> onClassLabels = getAnnotationsOnClass(result, labelAnnotation).stream()
                .map(extractor);
        labels.addAll(onClassLabels.collect(Collectors.toList()));
    }

    return labels.stream();
}
项目:sling-org-apache-sling-testing-rules    文件:RemoteLogDumperRule.java   
@Override
protected void failed(Throwable e, Description description) {
    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);

    if (slingClient != null) {
        try {
            SlingHttpResponse response = slingClient.doGet(SERVLET_PATH, URLParameterBuilder.create()
                    .add(TEST_CLASS_HEADER, description.getClassName())
                    .add(TEST_NAME_HEADER, description.getMethodName())
                    .getList(),
                    200);
            String msg = response.getSlingMessage();
            if (msg != null) {
                pw.println(msg);
            }

            pw.printf("=============== Logs from server [%s] for [%s]===================%n",
                    slingClient.getUrl(), description.getMethodName());
            pw.print(response.getContent());
            pw.println("========================================================");

            System.err.print(sw.toString());
        } catch (Throwable t) {
            System.err.printf("Error occurred while fetching test logs from server [%s] %n", slingClient.getUrl());
            t.printStackTrace(System.err);
        }
    } else {
        System.err.println("No SlingClient configured with the rule");
    }
}
项目:jwala    文件:IntegrationTestRule.java   
public Statement apply(final Statement base,
                       final Description description) {
    if (shouldRunIntegrationTests) {
        return base;
    } else {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                LOGGER.info("Skipping test because it's an integration test and they have not been configured to run: {}", description);
            }
        };
    }
}
项目:willtest    文件:LogContext.java   
@Override
public void after(Description description, Throwable testFailure) throws Throwable {
    super.after(description, testFailure);
    MDC.remove(TEST_CLASS);
    MDC.remove(TEST_DISPLAY_NAME);
    MDC.remove(TEST_METHOD);
}
项目:monarch    文件:SerializableRuleListTest.java   
@Override
public Statement apply(final Statement base, final Description description) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      base.evaluate();
    }
  };
}
项目:GitHub    文件:RecordingSubscriber.java   
@Override public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override public void evaluate() throws Throwable {
      base.evaluate();
      for (RecordingSubscriber<?> subscriber : subscribers) {
        subscriber.assertNoEvents();
      }
    }
  };
}
项目:smart-testing    文件:MavenExtensionSoftAssertions.java   
@Override
public Statement apply(Statement base, Description description) {
    return new Statement() {
        public void evaluate() throws Throwable {
            base.evaluate();
            assertAll();
        }
    };
}
项目:GitHub    文件:RecordingMaybeObserver.java   
@Override public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override public void evaluate() throws Throwable {
      base.evaluate();
      for (RecordingMaybeObserver<?> subscriber : subscribers) {
        subscriber.assertNoEvents();
      }
    }
  };
}
项目:testcontainers-junit    文件:GenericContainerRule.java   
/** {@inheritDoc} */
@Override
public Statement apply(Statement base, Description description) {
    container = containerSupplier.get();
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            List<Throwable> errors = new ArrayList<>();
            try {
                beforeStart(container);
                container.start();
                afterStart(container);
                beforeTest(container);
                base.evaluate();
                afterTest(container);
            } catch (Exception e) {
                errors.add(e);
                error(e);
            } finally {
                beforeStop(container);
                container.stop();
                afterStop(container);
            }

            MultipleFailureException.assertEmpty(errors);
        }
    };
}
项目:hekate    文件:HekateTestBase.java   
@Override
protected void failed(Throwable e, Description description) {
    if (e instanceof TestTimedOutException) {
        System.out.println(threadDump());
    }

    super.failed(e, description);
}
项目:embedded-jms-junit    文件:EmbeddedJmsRuleImpl.java   
private String getBrokerName(final Description description) {
    if (predefinedName == null) {
        return extractNameFromDescription(description);
    } else {
        return predefinedName;
    }
}
项目:allure-java    文件:AllureJunit4.java   
@Override
public void testFinished(final Description description) throws Exception {
    final String uuid = testCases.get();
    testCases.remove();
    getLifecycle().updateTestCase(uuid, testResult -> {
        if (Objects.isNull(testResult.getStatus())) {
            testResult.setStatus(Status.PASSED);
        }
    });

    getLifecycle().stopTestCase(uuid);
    getLifecycle().writeTestCase(uuid);
}
项目:GitHub    文件:InMemoryFileSystem.java   
@Override public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override public void evaluate() throws Throwable {
      base.evaluate();
      ensureResourcesClosed();
    }
  };
}
项目:sling-org-apache-sling-testing-rules    文件:TestStickyCookieRule.java   
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {

            starting(description);
            try {
                base.evaluate();
            } finally {
                finished(description);
            }
        }
    };
}