Java 类org.springframework.test.context.TestContext 实例源码

项目:embedded-database-spring-test    文件:OptimizedFlywayTestExecutionListener.java   
private void optimizedDbReset(TestContext testContext, FlywayTest annotation) throws Exception {
    if (annotation != null && annotation.invokeCleanDB() && annotation.invokeMigrateDB() && !annotation.invokeBaselineDB()) {

        ApplicationContext applicationContext = testContext.getApplicationContext();

        FlywayDataSourceContext dataSourceContext = getDataSourceContext(applicationContext, annotation.flywayName());
        Flyway flywayBean = ReflectionTestUtils.invokeMethod(this, "getBean", applicationContext, Flyway.class, annotation.flywayName());

        if (dataSourceContext != null && flywayBean != null) {
            prepareDataSourceContext(dataSourceContext, flywayBean, annotation);

            FlywayTest adjustedAnnotation = copyAnnotation(annotation, false, false, true);
            ReflectionTestUtils.invokeMethod(this, "dbResetWithAnnotation", testContext, adjustedAnnotation);

            return;
        }
    }

    ReflectionTestUtils.invokeMethod(this, "dbResetWithAnnotation", testContext, annotation);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:AutoConfigureReportTestExecutionListenerTests.java   
@Test
public void prepareFailingTestInstanceShouldPrintReport() throws Exception {
    TestContext testContext = mock(TestContext.class);
    given(testContext.getTestInstance()).willThrow(new IllegalStateException());
    SpringApplication application = new SpringApplication(Config.class);
    application.setWebEnvironment(false);
    ConfigurableApplicationContext applicationContext = application.run();
    given(testContext.getApplicationContext()).willReturn(applicationContext);
    try {
        this.reportListener.prepareTestInstance(testContext);
    }
    catch (IllegalStateException ex) {
        // Expected
    }
    this.out.expect(containsString("AUTO-CONFIGURATION REPORT"));
    this.out.expect(containsString("Positive matches"));
    this.out.expect(containsString("Negative matches"));
}
项目:allure-java    文件:AllureSpring4.java   
@Override
public void afterTestMethod(final TestContext testContext) throws Exception {
    final String uuid = testCases.get();
    testCases.remove();
    getLifecycle().updateTestCase(uuid, testResult -> {
        testResult.setStatus(getStatus(testContext.getTestException()).orElse(Status.PASSED));
        if (Objects.isNull(testResult.getStatusDetails())) {
            testResult.setStatusDetails(new StatusDetails());
        }
        getStatusDetails(testContext.getTestException()).ifPresent(statusDetails -> {
            testResult.getStatusDetails().setMessage(statusDetails.getMessage());
            testResult.getStatusDetails().setTrace(statusDetails.getTrace());
        });
    });
    getLifecycle().stopTestCase(uuid);
    getLifecycle().writeTestCase(uuid);
}
项目:easymall    文件:JunitCaseListener.java   
@Override
public void afterTestMethod(TestContext testContext)  {
    Method method = testContext.getTestMethod();
    if (DataSetAnnotationUtils.isRun(method)) {
        try {
            MybatisTestProcessor mybatisTestProcessor = testContext.
                    getApplicationContext().getBean(DataSetAnnotationUtils.getImplName(method));
            boolean success = mybatisTestProcessor.compareResult(method);
            if (!success) {
                logger.info("Data test result : failure");
                Assert.fail();
            }
        } catch (EasyMallTestException e) {
            logger.error(e.getMessage(), e);
            Assert.fail(e.getMessage());
        }
    }
    logger.info("Data test result : success");
    MDC.clear();
}
项目:easy-test    文件:JunitCaseListener.java   
@Override
public void afterTestMethod(TestContext testContext) {
    Method method = testContext.getTestMethod();
    if (DataSetAnnotationUtils.isRun(method)) {
        try {
            DataProcessor dataProcessor = testContext.
                    getApplicationContext().getBean(DataSetAnnotationUtils.getImplName(method));
            boolean success = dataProcessor.compareResult(method);
            if (!success) {
                logger.info("Data test result : failure");
                Assert.fail();
            }
        } catch (EasyTestException e) {
            logger.error(e.getMessage(), e);
            Assert.fail(e.getMessage());
        }
    }
    logger.info("Data test result : success");
    MDC.clear();
}
项目:wisp    文件:UnitTestTransactionalTestExecutionListener.java   
/**
 * 初始化数据源
 *
 * @param testContext
 */
private void initDatabase(TestContext testContext) {
    SqlConfig.Database database = null;
    Class<?> testClass = testContext.getTestClass();
    SqlConfig sqlConfigInClass = testClass.getAnnotation(SqlConfig.class);
    if (sqlConfigInClass != null) {
        database = sqlConfigInClass.database();
    }
    Method method = testContext.getTestMethod();
    SqlConfig sqlConfigInMethod = method.getAnnotation(SqlConfig.class);
    if (sqlConfigInMethod != null) {
        database = sqlConfigInMethod.database();
    }
    if (database != null) {
        UnitTestDataSource.selectDataSource(database);
    }
}
项目:springmock    文件:MockitoMockResetTestExecutionListener.java   
private void resetMocks(TestContext testContext, Predicate<MockitoDoubleConfiguration> shouldResetPredicate) throws Exception {
    final ApplicationContext applicationContext = testContext.getApplicationContext();
    final DoubleRegistry doubleRegistry = applicationContext.getBean(DoubleRegistry.BEAN_NAME, DoubleRegistry.class);
    final DoubleSearch doubleSearch = doubleRegistry.doublesSearch();

    for (DoubleDefinition doubleDefinition : doubleRegistry.doublesSearch()) {
        final String beanName = doubleDefinition.getName();
        final Object bean = applicationContext.getBean(beanName);
        if (Mockito.mockingDetails(bean).isMock()) {
            final DoubleDefinition definition = doubleSearch.findOneDefinition(beanName);
            final MockitoDoubleConfiguration configuration = definition.getConfiguration(MockitoDoubleConfiguration.class);

            if (shouldResetPredicate.test(configuration)) {
                mockResetExecutor.resetMock(bean);
            }
        }
    }
}
项目:springmock    文件:MockitoMockResetTestExecutionListenerTest.java   
@Test
public void should_reset_only_mocks_and_spies() throws Exception {
    //given
    final TestContext testContext = createTestContext(
            new DoubleRegistry(emptyList(), emptyList()),
            Stream.of(
                    bean("string1", "first string"),
                    bean("string2", "second string")));

    //when
    executionListener.beforeTestMethod(testContext);
    executionListener.afterTestMethod(testContext);

    //then
    Mockito.verifyZeroInteractions(resetExecutor);
}
项目:springmock    文件:MockitoMockResetTestExecutionListenerTest.java   
@Test
public void should_never_reset_mock() throws Exception {
    //given
    final Object mock = Mockito.mock(Object.class, "mock to reset");
    final String noResetMockName = "no reset mock";
    final TestContext testContext = createTestContext(
            new DoubleRegistry(
                    singletonList(
                            DoubleDefinition.builder()
                                    .name(noResetMockName)
                                    .doubleClass(Object.class)
                                    .doubleConfiguration(neverReset())
                                    .build()),
                    emptyList()),
            Stream.of(bean(noResetMockName, mock)));

    //when
    executionListener.beforeTestMethod(testContext);
    executionListener.afterTestMethod(testContext);

    //then
    Mockito.verifyZeroInteractions(resetExecutor);
}
项目:springmock    文件:MockAttachingTestExecutionListener.java   
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
    final Object testInstance = testContext.getTestInstance();
    if (!(testInstance instanceof Specification)) {
        return;
    }

    final Specification specification = (Specification) testInstance;
    final List<Object> mocks = new LinkedList<>();
    final ApplicationContext applicationContext = testContext.getApplicationContext();
    final DoubleRegistry doubleRegistry = applicationContext.getBean(DoubleRegistry.BEAN_NAME, DoubleRegistry.class);

    for (DoubleDefinition doubleDefinition : doubleRegistry.doublesSearch()) {
        final Optional<Object> doubleBean = tryToGetBean(applicationContext, doubleDefinition);

        doubleBean.ifPresent(bean -> {
            mocks.add(bean);
            mockUtil.attachMock(bean, specification);
        });
    }

    testContext.setAttribute(MOCKED_BEANS_NAMES, mocks);
}
项目:restdocs-wiremock    文件:WireMockListener.java   
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
    wireMockAnnotation = testContext.getTestClass().getAnnotation(WireMockTest.class);
    if(wireMockAnnotation == null) {
        return;
    }

    int port = wireMockAnnotation.port() > 0 ? wireMockAnnotation.port() : InetUtils.getFreeServerPort();
    ArrayList<String> properties = new ArrayList<>();
    properties.add("wiremock.port=" + port);
    properties.add("wiremock.enabled=true");
    properties.add("wiremock.stubPath=" + wireMockAnnotation.stubPath());
    properties.add("ribbon.eureka.enabled=false");
    for (String service : (String[]) wireMockAnnotation.ribbonServices()) {
        properties.add(service + ".ribbon.listOfServers=localhost:" + port);
    }

    addPropertySourceProperties(testContext, properties.toArray(new String[0]));
}
项目:spring4-understanding    文件:TransactionalTestExecutionListener.java   
/**
 * Get the {@linkplain PlatformTransactionManager transaction manager} to use
 * for the supplied {@linkplain TestContext test context} and {@code qualifier}.
 * <p>Delegates to {@link #getTransactionManager(TestContext)} if the
 * supplied {@code qualifier} is {@code null} or empty.
 * @param testContext the test context for which the transaction manager
 * should be retrieved
 * @param qualifier the qualifier for selecting between multiple bean matches;
 * may be {@code null} or empty
 * @return the transaction manager to use, or {@code null} if not found
 * @throws BeansException if an error occurs while retrieving the transaction manager
 * @see #getTransactionManager(TestContext)
 */
protected PlatformTransactionManager getTransactionManager(TestContext testContext, String qualifier) {
    // look up by type and qualifier from @Transactional
    if (StringUtils.hasText(qualifier)) {
        try {
            // Use autowire-capable factory in order to support extended qualifier
            // matching (only exposed on the internal BeanFactory, not on the
            // ApplicationContext).
            BeanFactory bf = testContext.getApplicationContext().getAutowireCapableBeanFactory();

            return BeanFactoryAnnotationUtils.qualifiedBeanOfType(bf, PlatformTransactionManager.class, qualifier);
        }
        catch (RuntimeException ex) {
            if (logger.isWarnEnabled()) {
                logger.warn(
                    String.format(
                        "Caught exception while retrieving transaction manager with qualifier '%s' for test context %s",
                        qualifier, testContext), ex);
            }
            throw ex;
        }
    }

    // else
    return getTransactionManager(testContext);
}
项目:spring4-understanding    文件:TransactionalTestExecutionListener.java   
/**
 * Determine whether or not to rollback transactions by default for the
 * supplied {@linkplain TestContext test context}.
 * <p>Supports {@link Rollback @Rollback} or
 * {@link TransactionConfiguration @TransactionConfiguration} at the
 * class-level.
 * @param testContext the test context for which the default rollback flag
 * should be retrieved
 * @return the <em>default rollback</em> flag for the supplied test context
 * @throws Exception if an error occurs while determining the default rollback flag
 */
@SuppressWarnings("deprecation")
protected final boolean isDefaultRollback(TestContext testContext) throws Exception {
    Class<?> testClass = testContext.getTestClass();
    Rollback rollback = findAnnotation(testClass, Rollback.class);
    boolean rollbackPresent = (rollback != null);
    TransactionConfigurationAttributes txConfigAttributes = retrieveConfigurationAttributes(testContext);

    if (rollbackPresent && txConfigAttributes != defaultTxConfigAttributes) {
        throw new IllegalStateException(String.format("Test class [%s] is annotated with both @Rollback "
                + "and @TransactionConfiguration, but only one is permitted.", testClass.getName()));
    }

    if (rollbackPresent) {
        boolean defaultRollback = rollback.value();
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Retrieved default @Rollback(%s) for test class [%s].", defaultRollback,
                testClass.getName()));
        }
        return defaultRollback;
    }

    // else
    return txConfigAttributes.isDefaultRollback();
}
项目:spring4-understanding    文件:TransactionalTestExecutionListener.java   
/**
 * Retrieve the {@link TransactionConfigurationAttributes} for the
 * supplied {@link TestContext} whose {@linkplain Class test class}
 * may optionally declare or inherit
 * {@link TransactionConfiguration @TransactionConfiguration}.
 * <p>If {@code @TransactionConfiguration} is not present for the
 * supplied {@code TestContext}, a default instance of
 * {@code TransactionConfigurationAttributes} will be used instead.
 * @param testContext the test context for which the configuration
 * attributes should be retrieved
 * @return the TransactionConfigurationAttributes instance for this listener,
 * potentially cached
 * @see TransactionConfigurationAttributes#TransactionConfigurationAttributes()
 */
@SuppressWarnings("deprecation")
TransactionConfigurationAttributes retrieveConfigurationAttributes(TestContext testContext) {
    if (this.configurationAttributes == null) {
        Class<?> clazz = testContext.getTestClass();

        TransactionConfiguration txConfig = AnnotatedElementUtils.findMergedAnnotation(clazz,
            TransactionConfiguration.class);
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Retrieved @TransactionConfiguration [%s] for test class [%s].",
                txConfig, clazz.getName()));
        }

        TransactionConfigurationAttributes configAttributes = (txConfig == null ? defaultTxConfigAttributes
                : new TransactionConfigurationAttributes(txConfig.transactionManager(), txConfig.defaultRollback()));

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Using TransactionConfigurationAttributes %s for test class [%s].",
                configAttributes, clazz.getName()));
        }
        this.configurationAttributes = configAttributes;
    }
    return this.configurationAttributes;
}
项目:spring4-understanding    文件:SqlScriptsTestExecutionListener.java   
/**
 * Execute SQL scripts configured via {@link Sql @Sql} for the supplied
 * {@link TestContext} and {@link ExecutionPhase}.
 */
private void executeSqlScripts(TestContext testContext, ExecutionPhase executionPhase) throws Exception {
    boolean classLevel = false;

    Set<Sql> sqlAnnotations = AnnotationUtils.getRepeatableAnnotations(testContext.getTestMethod(), Sql.class,
        SqlGroup.class);
    if (sqlAnnotations.isEmpty()) {
        sqlAnnotations = AnnotationUtils.getRepeatableAnnotations(testContext.getTestClass(), Sql.class,
            SqlGroup.class);
        if (!sqlAnnotations.isEmpty()) {
            classLevel = true;
        }
    }

    for (Sql sql : sqlAnnotations) {
        executeSqlScripts(sql, executionPhase, testContext, classLevel);
    }
}
项目:spring4-understanding    文件:AbstractDirtiesContextTestExecutionListener.java   
/**
 * Perform the actual work for {@link #beforeTestClass} and {@link #afterTestClass}
 * by dirtying the context if appropriate (i.e., according to the required mode).
 * @param testContext the test context whose application context should
 * potentially be marked as dirty; never {@code null}
 * @param requiredClassMode the class mode required for a context to
 * be marked dirty in the current phase; never {@code null}
 * @throws Exception allows any exception to propagate
 * @since 4.2
 * @see #dirtyContext
 */
protected void beforeOrAfterTestClass(TestContext testContext, ClassMode requiredClassMode) throws Exception {
    Assert.notNull(testContext, "TestContext must not be null");
    Assert.notNull(requiredClassMode, "requiredClassMode must not be null");

    Class<?> testClass = testContext.getTestClass();
    Assert.notNull(testClass, "The test class of the supplied TestContext must not be null");

    DirtiesContext dirtiesContext = AnnotatedElementUtils.findMergedAnnotation(testClass, DirtiesContext.class);
    boolean classAnnotated = (dirtiesContext != null);
    ClassMode classMode = (classAnnotated ? dirtiesContext.classMode() : null);

    if (logger.isDebugEnabled()) {
        String phase = (requiredClassMode.name().startsWith("BEFORE") ? "Before" : "After");
        logger.debug(String.format(
            "%s test class: context %s, class annotated with @DirtiesContext [%s] with mode [%s].", phase,
            testContext, classAnnotated, classMode));
    }

    if (classMode == requiredClassMode) {
        dirtyContext(testContext, dirtiesContext.hierarchyMode());
    }
}
项目:spring4-understanding    文件:ContextCacheTests.java   
@Test
public void removeContextHierarchyCacheLevel1() {

    // Load Level 3-A
    TestContext testContext3a = TestContextTestUtils.buildTestContext(
        ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache);
    testContext3a.getApplicationContext();
    assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3);
    assertParentContextCount(2);

    // Load Level 3-B
    TestContext testContext3b = TestContextTestUtils.buildTestContext(
        ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache);
    testContext3b.getApplicationContext();
    assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4);
    assertParentContextCount(2);

    // Remove Level 1
    // Should also remove Levels 2, 3-A, and 3-B, leaving nothing.
    contextCache.remove(getMergedContextConfiguration(testContext3a).getParent().getParent(),
        HierarchyMode.CURRENT_LEVEL);
    assertContextCacheStatistics(contextCache, "removed level 1", 0, 1, 4);
    assertParentContextCount(0);
}
项目:spring4-understanding    文件:ContextCacheTests.java   
@Test
public void removeContextHierarchyCacheLevel2() {

    // Load Level 3-A
    TestContext testContext3a = TestContextTestUtils.buildTestContext(
        ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache);
    testContext3a.getApplicationContext();
    assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3);
    assertParentContextCount(2);

    // Load Level 3-B
    TestContext testContext3b = TestContextTestUtils.buildTestContext(
        ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache);
    testContext3b.getApplicationContext();
    assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4);
    assertParentContextCount(2);

    // Remove Level 2
    // Should also remove Levels 3-A and 3-B, leaving only Level 1 as a context in the
    // cache but also removing the Level 1 hierarchy since all children have been
    // removed.
    contextCache.remove(getMergedContextConfiguration(testContext3a).getParent(), HierarchyMode.CURRENT_LEVEL);
    assertContextCacheStatistics(contextCache, "removed level 2", 1, 1, 4);
    assertParentContextCount(0);
}
项目:java8-spring-security-test    文件:WatchWithUserTestExecutionListener.java   
/**
 * Validate that a test has been executed for every mock/test user expected.  If any remain,
 * raise a failure.
 * @param testContext The TestContext being executed
 * @throws Exception if an Exception occurs
 */
@Override
public void afterTestClass(TestContext testContext) throws Exception {
    int errorCount = 0;
    for (String key : methodContextMap.keySet()) {
        TestMethodContext context = methodContextMap.get(key);
        if (context.getExecutionStack().size() > 0) {
            System.out.println(context.getExecutionStack().size() + " Unused SecurityUsers on " + key);
            errorCount++;
        }
    }

    if (errorCount > 0) {
        throw new AssertionFailedError("Unused SecurityUsers remaining on " + errorCount + " methods");
    }
}
项目:teasy    文件:SeleniumTestExecutionListener.java   
@Override
public void beforeTestMethod(TestContext context) throws Exception {
    setUseProxy(context);
    setAlertCapability(context);
    setNeedToRestart(context);
    setUseFireBug(context);

    if (getWebDriver() != null && useProxy.get()) {
        quitWebDriver();
    }

    if (getWebDriver() != null && !alertCapability.get().equals(currentAlertCapability.get())) {
        quitWebDriver();
    }

    //for force restart driver before start test
    if (getWebDriver() != null && isNeedToRestart.get()) {
        quitWebDriver();
    }

    if (getWebDriver() != null && isUseFireBug.get()) {
        quitWebDriver();
    }

    if (getWebDriver() == null) {
        prepareTestInstance(context);
    }
}
项目:teasy    文件:SeleniumTestExecutionListener.java   
private void setAlertCapability(TestContext context) {
    Method testMethod = context.getTestMethod();
    if (testMethod != null) {
        UnexpectedAlertCapability capability = testMethod.getAnnotation(UnexpectedAlertCapability.class);
        if (capability != null) {
            alertCapability.set(capability.capability());
        }
    }
}
项目:allure-java    文件:AllureSpring4.java   
@Override
public void beforeTestMethod(final TestContext testContext) throws Exception {
    final String uuid = testCases.get();
    final Class<?> testClass = testContext.getTestClass();
    final Method testMethod = testContext.getTestMethod();
    final String id = getHistoryId(testClass, testMethod);

    final TestResult result = new TestResult()
            .withUuid(uuid)
            .withHistoryId(id)
            .withName(testMethod.getName())
            .withFullName(String.format("%s.%s", testClass.getCanonicalName(), testMethod.getName()))
            .withLinks(getLinks(testClass, testMethod))
            .withLabels(
                    new Label().withName("package").withValue(testClass.getCanonicalName()),
                    new Label().withName("testClass").withValue(testClass.getCanonicalName()),
                    new Label().withName("testMethod").withValue(testMethod.getName()),

                    new Label().withName("suite").withValue(testClass.getName()),

                    new Label().withName("host").withValue(getHostName()),
                    new Label().withName("thread").withValue(getThreadName())
            );

    result.getLabels().addAll(getLabels(testClass, testMethod));
    getDisplayName(testMethod).ifPresent(result::setName);
    getLifecycle().scheduleTestCase(result);
    getLifecycle().startTestCase(uuid);
}
项目:easymall    文件:JunitCaseListener.java   
@Override
public void prepareTestInstance(TestContext testContext) {
    MDC.put("Trace", UUID.randomUUID().toString());
}
项目:easymall    文件:JunitCaseListener.java   
@Override
public void beforeTestMethod(TestContext testContext) {
    Method method = testContext.getTestMethod();
    if (DataSetAnnotationUtils.isRun(method)) {
        try{
            MybatisTestProcessor mybatisTestProcessor = testContext.
                    getApplicationContext().getBean(DataSetAnnotationUtils.getImplName(method));
            mybatisTestProcessor.insertPrepareData(method);
        } catch (EasyMallTestException e) {
            logger.error(e.getMessage(), e);
            Assert.fail(e.getMessage());
        }
    }
}
项目:uis    文件:FixedClockListener.java   
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
    FixedClock classFixedClock = AnnotationUtils.findAnnotation(testContext.getTestClass(), FixedClock.class);
    if (classFixedClock == null) {
        return;
    }
    mockClock(testContext, classFixedClock);
}
项目:uis    文件:FixedClockListener.java   
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
    FixedClock methodFixedClock = AnnotationUtils.findAnnotation(testContext.getTestMethod(), FixedClock.class);
    if (methodFixedClock == null) {
        return;
    }
    verifyClassAnnotation(testContext);
    mockClock(testContext, methodFixedClock);
}
项目:uis    文件:FixedClockListener.java   
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
    FixedClock methodFixedClock = AnnotationUtils.findAnnotation(testContext.getTestMethod(), FixedClock.class);
    if (methodFixedClock == null) {
        return;
    }
    verifyClassAnnotation(testContext);

    FixedClock classFixedClock = AnnotationUtils.findAnnotation(testContext.getTestClass(), FixedClock.class);
    mockClock(testContext, classFixedClock);
}
项目:uis    文件:FixedClockListener.java   
@Override
public void afterTestClass(TestContext testContext) throws Exception {
    FixedClock annotation = AnnotationUtils.findAnnotation(testContext.getTestClass(), FixedClock.class);
    if (annotation == null) {
        return;
    }
    //reset(testContext.getApplicationContext().getBean(Clock.class));
}
项目:OperatieBRP    文件:DBUnitLoaderTestExecutionListener.java   
@Override
public void afterTestClass(final TestContext testContext) throws Exception {
    LOGGER.debug("teardown DBUnit databaseTester");
    if (databaseTester != null) {
        databaseTester.onTearDown();
    }
}
项目:easy-test    文件:JunitCaseListener.java   
@Override
public void beforeTestMethod(TestContext testContext) {
    Method method = testContext.getTestMethod();
    if (DataSetAnnotationUtils.isRun(method)) {
        try {
            DataProcessor dataProcessor = testContext.
                    getApplicationContext().getBean(DataSetAnnotationUtils.getImplName(method));
            dataProcessor.insertPrepareData(method);
        } catch (EasyTestException e) {
            logger.error(e.getMessage(), e);
            Assert.fail(e.getMessage());
        }
    }
}
项目:wisp    文件:UnitTestDependencyInjectionTestExecutionListener.java   
@Override
protected void injectDependencies(TestContext testContext) throws Exception {
    super.injectDependencies(testContext);
    /**
     * 获取测试类 & fields
     */
    Object bean = testContext.getTestInstance();
    List<Field> fields = getDeclaredFields(bean);
    if (CollectionUtils.isEmpty(fields)) {
        return;
    }
    /**
     * 如果测试类中, 被测试对象含有mockito的@InjectMocks注解,且 被测试对象被事务拦截器拦截 则 用原始对象代替
     */
    for (Field field : fields) {
        InjectMocks injectMocks = field.getAnnotation(InjectMocks.class);
        if (injectMocks == null) {
            continue;
        }
        field.setAccessible(true);
        Object proxy = field.get(bean);
        if (AopUtils.isAopProxy(proxy)) {
            // 替换对象
            Object target = ((Advised) proxy).getTargetSource().getTarget();
            field.set(bean, target);
        }
    }
}
项目:wisp    文件:UnitTestDependencyInjectionTestExecutionListener.java   
@Override
public void afterTestClass(TestContext testContext) throws Exception {
    super.afterTestClass(testContext);
    /**
     * 重新注册被污染的bean
     */
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) testContext.getApplicationContext()
            .getAutowireCapableBeanFactory();
    for (Entry<String, Object> entry : testedObjects.entrySet()) {
        BeanDefinition beanDefinition = beanFactory.getBeanDefinition(entry.getKey());
        beanFactory.removeBeanDefinition(entry.getKey());
        beanFactory.registerBeanDefinition(entry.getKey(), beanDefinition);
    }
}
项目:wisp    文件:UnitTestTransactionalTestExecutionListener.java   
private void initTestData(TestContext testContext) {
    List<String> sqlFiles = new ArrayList<String>();
    /**
     * 读取测试类指定的sql文件
     */
    Class<?> testClass = testContext.getTestClass();
    SqlConfig sqlConfigInClass = testClass.getAnnotation(SqlConfig.class);
    if (sqlConfigInClass != null) {
        String[] sqlFilesInClass = sqlConfigInClass.sqlFiles();
        if (ArrayUtils.isNotEmpty(sqlFilesInClass)) {
            sqlFiles.addAll(Arrays.asList(sqlFilesInClass));
        }
    }
    /**
     * 读取测试方法指定的sql文件
     */
    Method method = testContext.getTestMethod();
    SqlConfig sqlConfigInMethod = method.getAnnotation(SqlConfig.class);
    if (sqlConfigInMethod != null) {
        String[] sqlFilesInMethod = sqlConfigInMethod.sqlFiles();
        if (ArrayUtils.isNotEmpty(sqlFilesInMethod)) {
            sqlFiles.addAll(Arrays.asList(sqlFilesInMethod));
        }
    }
    /**
     * 执行sql
     */
    for (String sqlFile : sqlFiles) {
        LOGGER.info(String.format("execute sql file [%s]", sqlFile));
        this.executeSqlScript(testContext, sqlFile, false);
    }
}
项目:springmock    文件:MockitoMockResetTestExecutionListenerTest.java   
@Test
public void should_reset_all_mocks_after_test_method() throws Exception {
    //given
    final Object mock1 = Mockito.mock(Object.class);
    final Object mock2 = Mockito.mock(Object.class);
    final TestContext testContext = createTestContext(
            new DoubleRegistry(
                    asList(
                            DoubleDefinition.builder()
                                    .name("mock1")
                                    .doubleClass(Object.class)
                                    .doubleConfiguration(resetAfterTestMethod())
                                    .build(),
                            DoubleDefinition.builder()
                                    .name("mock2")
                                    .doubleClass(Object.class)
                                    .doubleConfiguration(resetAfterTestMethod())
                                    .build()),
                    emptyList()),
            Stream.of(
                    bean("string", "first string"),
                    bean("mock1", mock1),
                    bean("mock2", mock2)));

    //when
    executionListener.afterTestMethod(testContext);

    //then
    Mockito
            .verify(resetExecutor)
            .resetMock(mock1);
    Mockito
            .verify(resetExecutor)
            .resetMock(mock2);
    Mockito.verifyNoMoreInteractions(resetExecutor);
}
项目:springmock    文件:MockitoMockResetTestExecutionListenerTest.java   
@Test
public void should_reset_all_spies_after_test_method() throws Exception {
    //given
    final Object spy1 = Mockito.spy(new Object());
    final Object spy2 = Mockito.spy(new Object());
    final TestContext testContext = createTestContext(
            new DoubleRegistry(
                    emptyList(),
                    asList(
                            DoubleDefinition.builder()
                                    .name("spy1")
                                    .doubleClass(Object.class)
                                    .doubleConfiguration(resetAfterTestMethod())
                                    .build(),
                            DoubleDefinition.builder()
                                    .name("spy2")
                                    .doubleClass(Object.class)
                                    .doubleConfiguration(resetAfterTestMethod())
                                    .build())),
            Stream.of(
                    bean("string", "first string"),
                    bean("spy1", spy1),
                    bean("spy2", spy2)));

    //when
    executionListener.afterTestMethod(testContext);

    //then
    Mockito
            .verify(resetExecutor)
            .resetMock(spy1);
    Mockito
            .verify(resetExecutor)
            .resetMock(spy2);
    Mockito.verifyNoMoreInteractions(resetExecutor);
}
项目:springmock    文件:MockitoMockResetTestExecutionListenerTest.java   
@Test
public void should_reset_mock_before_test_method() throws Exception {
    //given
    final Object mock = Mockito.mock(Object.class);
    final String mockName = "mock";
    final String noResetMockName = "no reset mock";
    final TestContext testContext = createTestContext(
            new DoubleRegistry(
                    asList(
                            DoubleDefinition.builder()
                                    .name(mockName)
                                    .doubleClass(Object.class)
                                    .doubleConfiguration(resetBeforeTestMethod())
                                    .build(),
                            DoubleDefinition.builder()
                                    .name(noResetMockName)
                                    .doubleClass(Object.class)
                                    .doubleConfiguration(neverReset())
                                    .build()),
                    emptyList()),
            Stream.of(
                    bean(noResetMockName, Mockito.mock(Object.class)),
                    bean(mockName, mock)));

    //when
    executionListener.beforeTestMethod(testContext);

    //then
    Mockito
            .verify(resetExecutor)
            .resetMock(mock);
    Mockito.verifyNoMoreInteractions(resetExecutor);
}
项目:springmock    文件:MockitoMockResetTestExecutionListenerTest.java   
@Test
public void should_reset_mocks_from_parent_context() throws Exception {
    //given
    final Object parentMock = Mockito.mock(Object.class);
    final Object childSpy = Mockito.mock(Object.class);
    final DoubleRegistry doubleRegistry = new DoubleRegistry(
            singletonList(DoubleDefinition.builder()
                    .name("parentMock")
                    .doubleClass(Object.class)
                    .doubleConfiguration(resetBeforeTestMethod())
                    .build()),
            singletonList(DoubleDefinition.builder()
                    .name("childSpy")
                    .doubleClass(Object.class)
                    .doubleConfiguration(resetAfterTestMethod())
                    .build()));
    final ApplicationContext parentContext = buildAppContext(Stream.of(bean("parentMock", parentMock)));
    final ApplicationContext middleContext = buildAppContext(parentContext, Stream.of(bean("childSpy", childSpy)));
    final ApplicationContext childContext = buildAppContext(middleContext, Stream.of(withDoubleRegistry(doubleRegistry)));
    final TestContext testContext = mockTestContext(childContext);

    //when
    executionListener.beforeTestMethod(testContext);
    executionListener.afterTestMethod(testContext);

    //then
    Mockito
            .verify(resetExecutor)
            .resetMock(parentMock);
    Mockito
            .verify(resetExecutor)
            .resetMock(childSpy);
}
项目:springmock    文件:MockitoMockResetTestExecutionListenerTest.java   
private TestContext mockTestContext(ApplicationContext applicationContext) {
    final TestContext testContext = Mockito.mock(TestContext.class);
    Mockito
            .when(testContext.getApplicationContext())
            .thenReturn(applicationContext);
    return testContext;
}
项目:spring-boot-concourse    文件:SpringApplicationContextLoaderTests.java   
private Map<String, Object> getEnvironmentProperties(Class<?> testClass)
        throws Exception {
    TestContext context = new ExposedTestContextManager(testClass)
            .getExposedTestContext();
    new IntegrationTestPropertiesListener().prepareTestInstance(context);
    MergedContextConfiguration config = (MergedContextConfiguration) ReflectionTestUtils
            .getField(context, "mergedContextConfiguration");
    return TestPropertySourceUtils
            .convertInlinedPropertiesToMap(config.getPropertySourceProperties());
}
项目:Camel    文件:StopWatchTestExecutionListener.java   
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
    StopWatch watch = threadStopWatch.get();
    if (watch != null) {
        long time = watch.stop();
        Logger log = LoggerFactory.getLogger(testContext.getTestClass());

        log.info("********************************************************************************");
        log.info("Testing done: " + testContext.getTestMethod().getName() + "(" + testContext.getTestClass().getName() + ")");
        log.info("Took: " + TimeUtils.printDuration(time) + " (" + time + " millis)");
        log.info("********************************************************************************");

        threadStopWatch.remove();
    }
}