Java 类org.junit.jupiter.api.extension.ExtensionContext 实例源码

项目:junit-extensions    文件:ExpectedExceptionExtension.java   
/**
 * Handle the supplied {@code Throwable throwable}. If the {@code extensionContext} is annotated
 * with {@link ExpectedException} and if the {@code throwable} matches the expectations expressed
 * in the {@link ExpectedException} annotation then the supplied {@code throwable} is swallowed
 * otherwise the supplied {@code throwable} is rethrown.
 *
 * @param extensionContext the current extension context
 * @param throwable the {@code Throwable} to handle
 * @throws Throwable
 */
@Override
public void handleTestExecutionException(ExtensionContext extensionContext, Throwable throwable)
    throws Throwable {
  Optional<ExpectedException> optional =
      findAnnotation(extensionContext.getTestMethod(), ExpectedException.class);
  if (optional.isPresent()) {
    ExpectedException annotation = optional.get();
    if (throwable.getClass() == annotation.type()) {
      if (where(function, getPredicate(annotation)).test(throwable)) {
        return;
      }
    }
  }
  throw throwable;
}
项目:solidity-ide    文件:InjectorProviders.java   
public static IInjectorProvider getOrCreateInjectorProvider(ExtensionContext context) {
    InjectWith injectWith = context.getRequiredTestClass().getAnnotation(InjectWith.class);
    if (injectWith != null) {
        Class<? extends IInjectorProvider> klass = injectWith.value();
        IInjectorProvider injectorProvider = injectorProviderClassCache.get(klass);
        if (injectorProvider == null) {
            try {
                injectorProvider = klass.newInstance();
                injectorProviderClassCache.put(klass, injectorProvider);
            } catch (Exception e) {
                throwUncheckedException(e);
            }
        }
        return injectorProvider;
    }
    return null;
}
项目:junit5-extensions    文件:MockitoExtension.java   
@Override
public Object resolveParameter(ParameterContext parameterContext,
    ExtensionContext extensionContext)
    throws ParameterResolutionException {
  List<ParameterFactory> validFactories =
      getSupportedFactories(parameterContext.getParameter()).collect(toList());

  if (validFactories.size() > 1) {
    throw new ParameterResolutionException(
        String.format("Too many factories: %s for parameter: %s",
            validFactories,
            parameterContext.getParameter()));
  }

  return Iterables.getOnlyElement(validFactories)
      .getParameterValue(parameterContext.getParameter());
}
项目:junit5-extensions    文件:ExpectFailureExceptionHandler.java   
@Override
public void handleTestExecutionException(ExtensionContext context, Throwable throwable)
    throws Throwable {
  Optional<ExpectFailure> annotation = getAnnotation(context);

  if (!annotation.isPresent()) {
    throw throwable;
  }

  ExpectFailure expectedFailure = annotation.get();
  context.getStore(NAMESPACE).put(expectedFailure, throwable);

  ThrowableSubject subject = assertThat(throwable);
  for (Cause cause : expectedFailure.value()) {
    subject.isInstanceOf(cause.type());
    if (!cause.message().isEmpty()) {
      subject.hasMessageThat().contains(cause.message());
    }
    subject = subject.hasCauseThat();
  }
}
项目:junit5-extensions    文件:GuiceExtension.java   
/**
 * Returns module types that are present on the given context or any of its enclosing contexts.
 */
private static Set<Class<? extends Module>> getContextModuleTypes(
    Optional<ExtensionContext> context) {
  // TODO: Cache?

  Set<Class<? extends Module>> contextModuleTypes = new LinkedHashSet<>();
  while (context.isPresent() && (hasAnnotatedElement(context) || hasParent(context))) {
    context
        .flatMap(ExtensionContext::getElement)
        .map(GuiceExtension::getModuleTypes)
        .ifPresent(contextModuleTypes::addAll);
    context = context.flatMap(ExtensionContext::getParent);
  }

  return contextModuleTypes;
}
项目:qpp-conversion-tool    文件:RestExtension.java   
@Override
public void beforeAll(ExtensionContext context) throws Exception {
    Optional<String> baseUri = getProperty(BASE_URI_PROPERTY);
    Optional<String> port = getProperty(DEPLOY_PORT_PROPERTY);

    RestAssured.port = Integer.parseInt(port.orElse("8080"));
    RestAssured.baseURI = baseUri.map(host -> "http://" + host).orElse(RestAssured.DEFAULT_URI);
    RestAssured.rootPath = ROOT_PATH;

    waitForIt(baseUri.orElse("localhost"), RestAssured.port);
}
项目:solidity-ide    文件:InjectionExtension.java   
@Override
public void afterTestExecution(ExtensionContext context) throws Exception {
    IInjectorProvider injectorProvider = getOrCreateInjectorProvider(context);
    if (injectorProvider instanceof IRegistryConfigurator) {
        final IRegistryConfigurator registryConfigurator = (IRegistryConfigurator) injectorProvider;
        registryConfigurator.restoreRegistry();
    }
}
项目:mastering-junit5    文件:CustomArgumentsProvider2.java   
@Override
public Stream<? extends Arguments> provideArguments(
        ExtensionContext context) {

    System.out.println("Arguments provider [2] to test "
            + context.getTestMethod().get().getName());

    return Stream.of(Arguments.of("more", 3), Arguments.of("arguments", 4));
}
项目:mastering-junit5    文件:MockitoExtension.java   
private Object getMock(Parameter parameter,
        ExtensionContext extensionContext) {
    Class<?> mockType = parameter.getType();
    Store mocks = extensionContext
            .getStore(Namespace.create(MockitoExtension.class, mockType));
    String mockName = getMockName(parameter);

    if (mockName != null) {
        return mocks.getOrComputeIfAbsent(mockName,
                key -> mock(mockType, mockName));
    } else {
        return mocks.getOrComputeIfAbsent(mockType.getCanonicalName(),
                key -> mock(mockType));
    }
}
项目:mastering-junit5    文件:MockitoExtension.java   
private Object getMock(Parameter parameter,
        ExtensionContext extensionContext) {
    Class<?> mockType = parameter.getType();
    Store mocks = extensionContext
            .getStore(Namespace.create(MockitoExtension.class, mockType));
    String mockName = getMockName(parameter);

    if (mockName != null) {
        return mocks.getOrComputeIfAbsent(mockName,
                key -> mock(mockType, mockName));
    } else {
        return mocks.getOrComputeIfAbsent(mockType.getCanonicalName(),
                key -> mock(mockType));
    }
}
项目:Mastering-Software-Testing-with-JUnit-5    文件:IgnoreIOExceptionExtension.java   
@Override
public void handleTestExecutionException(ExtensionContext context,
        Throwable throwable) throws Throwable {

    if (throwable instanceof IOException) {
        return;
    }
    throw throwable;
}
项目:mastering-junit5    文件:IgnoreIOExceptionExtension.java   
@Override
public void handleTestExecutionException(ExtensionContext context,
        Throwable throwable) throws Throwable {

    if (throwable instanceof IOException) {
        return;
    }
    throw throwable;
}
项目:junit-extensions    文件:TestNameExtension.java   
private Optional<Field> getTestNameField(ExtensionContext extensionContext) {
  for (Field field : extensionContext.getRequiredTestClass().getDeclaredFields()) {
    if (isAnnotated(field, TestName.class)) {
      return Optional.of(field);
    }
  }
  return Optional.empty();
}
项目:testee.fi    文件:TestEEfi.java   
@Override
public void afterAll(final ExtensionContext context) throws Exception {
    final TestSetup testSetup = (TestSetup) context.getStore(NS).get(TestSetup.class);
    if (testSetup != null) {
        testSetup.shutdown();
    }

}
项目:solidity-ide    文件:InjectionExtension.java   
@Override
public void beforeTestExecution(ExtensionContext context) throws Exception {
    IInjectorProvider injectorProvider = getOrCreateInjectorProvider(context);
    if (injectorProvider instanceof IRegistryConfigurator) {
        final IRegistryConfigurator registryConfigurator = (IRegistryConfigurator) injectorProvider;
        registryConfigurator.setupRegistry();
    }
    if (injectorProvider != null) {
        Injector injector = injectorProvider.getInjector();
        if (injector != null)
            injector.injectMembers(context.getRequiredTestInstance());
    }
}
项目:testing-video    文件:GenerateVideoExtension.java   
@Override
public void beforeAll(ExtensionContext context) throws Exception {
    if (!STARTED) {
        out.println("Starting JavaFX");
        Platform.startup(() -> {});
        STARTED = true;
    }
}
项目:open-kilda    文件:MockitoExtension.java   
private Object getMock(Parameter parameter, ExtensionContext extensionContext) {
    Class<?> mockType = parameter.getType();
    Store mocks = extensionContext.getStore(Namespace.create(MockitoExtension.class, mockType));
    String mockName = getMockName(parameter);

    if (mockName != null) {
        return mocks.getOrComputeIfAbsent(mockName, key -> mock(mockType, mockName));
    }
    return mocks.getOrComputeIfAbsent(mockType.getCanonicalName(), key -> mock(mockType));
}
项目:golden-master    文件:RunInvocationContextProvider.java   
@Override
public void afterTestExecution(ExtensionContext context) throws Exception {
    Approval<File> approval = Approval.of(File.class)//
            .withPathMapper(pathMapper)//
            // TODO #3 Fork and suggest fix
            .withConveter(new FileConverter())//
            .withReporter(get(context, JUnitReporter.class, REPORTER_KEY)).build();

    String fileName = context.getRequiredTestMethod().getName() + ".approved";
    approval.verify(outputFile, Paths.get(fileName));
}
项目:golden-master    文件:TemplatedTestPathMapper.java   
public TemplatedTestPathMapper(ExtensionContext context, Path path) {
    Class<?> testClass = context.getRequiredTestClass();
    Method testMethod = context.getRequiredTestMethod();
    String runIdSuffix = getRunIdSuffix(context.getDisplayName());

    currentTestPath = path.resolve(testClass.getName().replace(".", File.separator))
            .resolve(testMethod.getName() + runIdSuffix);
}
项目:allure-java    文件:AllureJunit5AnnotationProcessor.java   
@Override
public void beforeTestExecution(final ExtensionContext context) throws Exception {
    getLifecycle().getCurrentTestCase().ifPresent(uuid -> {
        getLifecycle().updateTestCase(uuid, testResult -> {
            context.getTestClass().ifPresent(testClass -> {
                testResult.getLabels().addAll(getLabels(testClass));
                testResult.getLinks().addAll(getLinks(testClass));
            });
            context.getTestMethod().ifPresent(testMethod -> {
                testResult.getLabels().addAll(getLabels(testMethod));
                testResult.getLinks().addAll(getLinks(testMethod));
            });
        });
    });
}
项目:selenium-jupiter    文件:ForcedAnnotationReaderTest.java   
@ParameterizedTest
@MethodSource("forcedTestProvider")
void forcedTest(Class<? extends DriverHandler> handler, Class<?> testClass,
        Class<?> driverClass, String testName) throws Exception {
    Parameter parameter = testClass.getMethod(testName, driverClass)
            .getParameters()[0];
    assertThrows(SeleniumJupiterException.class, () -> {
        handler.getDeclaredConstructor(Parameter.class,
                ExtensionContext.class).newInstance(parameter, null)
                .resolve();
    });
}
项目:wiremock-junit5    文件:WiremockResolver.java   
@Override
public void afterEach(ExtensionContext testExtensionContext) throws Exception {
    if (server == null || !server.isRunning()) {
        return;
    }

    server.resetRequests();
    server.resetToDefaultMappings();
    log.info("Stopping wiremock server on localhost:{}", server.port());
    server.stop();
}
项目:selenium-jupiter    文件:SeleniumExtension.java   
@Override
public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(
        ExtensionContext context) {
    BrowsersTemplate browsers = null;
    try {
        String browserJsonContent = getString(
                "sel.jup.browser.template.json.content");

        if (browserJsonContent.isEmpty()) {
            String browserJsonFile = getString(
                    "sel.jup.browser.template.json.file");
            if (browserJsonFile.startsWith(CLASSPATH_PREFIX)) {
                String browserJsonInClasspath = browserJsonFile
                        .substring(CLASSPATH_PREFIX.length());
                browserJsonContent = IOUtils.toString(
                        this.getClass().getResourceAsStream(
                                "/" + browserJsonInClasspath),
                        defaultCharset());
            } else {
                browserJsonContent = new String(
                        readAllBytes(get(browserJsonFile)));
            }
        }

        browsers = new Gson().fromJson(browserJsonContent,
                BrowsersTemplate.class);

    } catch (IOException e) {
        throw new SeleniumJupiterException(e);
    }
    return browsers.getStream().map(b -> invocationContext(b, this));
}
项目:jwebassembly    文件:MockitoExtension.java   
private Object getMock(Parameter parameter, ExtensionContext extensionContext) {
    Class<?> mockType = parameter.getType();
    ExtensionContext.Store mocks = extensionContext.getStore(ExtensionContext.Namespace.create(MockitoExtension.class, mockType));
    String mockName = getMockName(parameter);

    if (mockName != null) {
        return mocks.getOrComputeIfAbsent(mockName, key -> mock(mockType, mockName));
    } else {
        return mocks.getOrComputeIfAbsent(mockType.getCanonicalName(), key -> mock(mockType));
    }
}
项目:traute    文件:AbstractTrauteExtension.java   
@Override
public final void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception {
    for (Class<?> clazz = testInstance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.getType() == TestCompiler.class) {
                field.setAccessible(true);
                field.set(testInstance, getCompiler());
            } else if (field.getType() == TestRunner.class) {
                field.setAccessible(true);
                field.set(testInstance, TrauteInMemoryTestRunner.INSTANCE);
            }
        }
    }
}
项目:junit5-extensions    文件:GuiceExtension.java   
@Override
public Object resolveParameter(ParameterContext parameterContext,
    ExtensionContext extensionContext)
    throws ParameterResolutionException {
  Parameter parameter = parameterContext.getParameter();
  Key<?> key = getKey(extensionContext.getTestClass(), parameter);
  Injector injector = getInjectorForParameterResolution(extensionContext)
      .orElseThrow(() ->
          new ParameterResolutionException(
              String.format(
                  "Could not create injector for: %s It has no annotated element.",
                  extensionContext.getDisplayName())));

  return injector.getInstance(key);
}
项目:solidity-ide    文件:InjectorProviders.java   
public static IInjectorProvider getInjectorProvider(ExtensionContext context) {
    InjectWith injectWith = context.getRequiredTestClass().getAnnotation(InjectWith.class);
    if (injectWith != null) {
        return injectorProviderClassCache.get(injectWith.value());
    }
    return null;
}
项目:junit-extensions    文件:WatcherExtension.java   
/**
 * Log test method exit, using the start time stored by {@link
 * #beforeTestExecution(ExtensionContext)} to calculate a duration.
 *
 * @param extensionContext the <em>context</em> in which the current test or container is being
 *     executed
 * @throws Exception
 */
@Override
public void afterTestExecution(ExtensionContext extensionContext) throws Exception {
  Method testMethod = extensionContext.getRequiredTestMethod();
  long start = getStore(extensionContext).remove(testMethod, long.class);
  long duration = System.currentTimeMillis() - start;

  logger.info(String.format("Completed test [%s] in %sms", testMethod.getName(), duration));
}
项目:roboslack    文件:SlackWebHookServiceTests.java   
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception {
    return Stream.of(
            MESSAGE_SIMPLE,
            MESSAGE_MARKDOWN_IN_ATTACHMENT_PRETEXT,
            MESSAGE_MARKDOWN_IN_PLAINTEXT_ATTACHMENT_FIELDS,
            MESSAGE_MARKDOWN_IN_ATTACHMENT_TEXT,
            MESSAGE_MARKDOWN_IN_ATTACHMENT_FIELDS,
            MESSAGE_WITH_ATTACHMENT_FOOTER,
            MESSAGE_WITH_ATTACHMENTS,
            MESSAGE_COMPLEX
    ).map(Arguments::of);
}
项目:Mastering-Software-Testing-with-JUnit-5    文件:CustomArgumentsProvider2.java   
@Override
public Stream<? extends Arguments> provideArguments(
        ExtensionContext context) {

    System.out.println("Arguments provider [2] to test "
            + context.getTestMethod().get().getName());

    return Stream.of(Arguments.of("more", 3), Arguments.of("arguments", 4));
}
项目:junit5-conditional-execution-extensions    文件:DisabledWhenExtension.java   
@Override
public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionContext context) {
  return context.getElement()
                .flatMap(annotatedElement -> findAnnotation(annotatedElement, DisabledWhen.class))
                .map(DisabledWhen::value)
                .map(supplierClass -> ReflectionSupport.newInstance(supplierClass))
                .map(Supplier::get)
                .map(result -> Objects.requireNonNull(result, "Supplier result must not be null"))
                .map(shouldDisable -> shouldDisable
                    ? disabled(DisabledWhen.class + " evaluated to true")
                    : enabled(DisabledWhen.class + " evaluated to false"))
                .orElse(DEFAULT);
}
项目:junit5-extensions    文件:GuiceExtension.java   
private static Injector createInjector(ExtensionContext context)
    throws NoSuchMethodException,
    InstantiationException,
    IllegalAccessException,
    InvocationTargetException {
  Optional<Injector> parentInjector = getParentInjector(context);
  List<? extends Module> modules = getNewModules(context);

  return parentInjector
      .map(injector -> injector.createChildInjector(modules))
      .orElseGet(() -> Guice.createInjector(modules));
}
项目:junit5-extensions    文件:GuiceExtension.java   
private static Optional<Injector> getParentInjector(ExtensionContext context)
    throws NoSuchMethodException,
    InstantiationException,
    IllegalAccessException,
    InvocationTargetException {
  if (context.getParent().isPresent()) {
    return getOrCreateInjector(context.getParent().get());
  }

  return Optional.empty();
}
项目:junit5-conditional-execution-extensions    文件:RunOnDayCondition.java   
@Override
public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionContext context) {
  return context.getElement()
                .flatMap(annotatedElement -> findAnnotation(annotatedElement, RunOnDay.class))
                .map(RunOnDay::value)
                .map(RunOnDayCondition::evaluateIfRunningOnDay)
                .orElse(DEFAULT);
}
项目:selenium-jupiter    文件:MockitoExtension.java   
@Override
public boolean supportsParameter(ParameterContext parameterContext,
        ExtensionContext extensionContext) {
    return parameterContext.getParameter().isAnnotationPresent(Mock.class);
}
项目:roboslack    文件:FooterTests.java   
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception {
    return ResourcesReader.readJson(RESOURCES_DIRECTORY).map(Arguments::of);
}
项目:qpp-conversion-tool    文件:MockitoExtension.java   
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
    return getMock(parameterContext.getParameter(), extensionContext);
}
项目:Mastering-Software-Testing-with-JUnit-5    文件:TimingExtension.java   
@Override
public void beforeTestExecution(ExtensionContext context) throws Exception {
    getStore(context).put(context.getRequiredTestMethod(),
            System.currentTimeMillis());
}
项目:vaadin-016-helloworld-14    文件:PageObjectExtension.java   
@Override
//  public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
  public boolean supports(ParameterContext parameterContext, ExtensionContext extensionContext)
      throws ParameterResolutionException {
    return parameterContext.getParameter().isAnnotationPresent(PageObject.class);
  }
项目:selenium-jupiter    文件:AppiumDriverHandler.java   
public AppiumDriverHandler(Parameter parameter, ExtensionContext context) {
    super(parameter, context);
}