org.springframework.test.context.TestContext Java Examples

The following examples show how to use org.springframework.test.context.TestContext. 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: TransactionalTestExecutionListener.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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)
 */
@Nullable
protected PlatformTransactionManager getTransactionManager(TestContext testContext, @Nullable 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);
}
 
Example #2
Source File: TransactionalTestExecutionListenerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-13895
public void transactionalTestWithoutTransactionManager() throws Exception {
	TransactionalTestExecutionListener listener = new TransactionalTestExecutionListener() {
		protected PlatformTransactionManager getTransactionManager(TestContext testContext, String qualifier) {
			return null;
		}
	};

	Class<? extends Invocable> clazz = TransactionalDeclaredOnClassLocallyTestCase.class;
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz);
	Invocable instance = BeanUtils.instantiateClass(clazz);
	given(testContext.getTestInstance()).willReturn(instance);
	given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("transactionalTest"));

	assertFalse("callback should not have been invoked", instance.invoked());
	TransactionContextHolder.removeCurrentTransactionContext();

	try {
		listener.beforeTestMethod(testContext);
		fail("Should have thrown an IllegalStateException");
	}
	catch (IllegalStateException e) {
		assertTrue(e.getMessage().startsWith(
				"Failed to retrieve PlatformTransactionManager for @Transactional test"));
	}
}
 
Example #3
Source File: TestMongoKeeper.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
/**
 * JSONファイルの検索場所候補を作成します。
 * この候補は、同一パッケージ内の、
 * <ol>
 *  <li>クラス名-メソッド名.json</li>
 *  <li>クラス名.json</li>
 *  <li>MongoInitaize.json</li>
 * </ol>
 * です。
 * @param context 現在のテスト実行コンテキスト
 * @param config コンフィグ
 * @return JSONファイルの検索場所候補の配列
 */
protected String[] createFileLocationCandidates(TestContext context, MongoInitialize config) {
    if (config.file().equals("")) {
        // クラス名-メソッド名 ex)/jp/co/ctc_g/jfw/sample/Sample-method
        String clazzMethod = Strings.join(
                "/",
                context.getTestClass().getName().replace(".", "/"),
                "-",
                context.getTestMethod().getName());
        // クラス名 ex)/jp/co/ctc_g/jfw/sample/Sample
        String clazz = Strings.join(
                "/",
                context.getTestClass().getName().replace(".", "/"));
        // パッケージ ex)/jp/co/ctc_g/jfw/sample/DatabaseInitialize
        String pakkage = Strings.join(
                "/",
                context.getTestClass().getPackage().getName().replace(".", "/"),
                "/",
                MongoInitialize.class.getSimpleName());
        return Arrays.gen(clazzMethod, clazz, pakkage);
    } else {
        return Arrays.gen(config.file());
    }
}
 
Example #4
Source File: TestDatabaseKeeper.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
/**
 * SQLファイルの検索場所候補を作成します。
 * この候補は、同一パッケージ内の、
 * <ol>
 *  <li>クラス名-メソッド名.sql</li>
 *  <li>クラス名.sql</li>
 *  <li>DatabaseInitialize.sql</li>
 * </ol>
 * です。
 * @param context 現在のテスト実行コンテキスト
 * @param config コンフィグ
 * @return SQLファイルの検索場所候補の配列
 */
protected String[] createFileLocationCandidates(TestContext context, DatabaseInitialize config) {
    if (config.file().equals("")) {
        // クラス名-メソッド名 ex)/jp/co/ctc_g/jfw/sample/Sample-method
        String clazzMethod = Strings.join(
                "/",
                context.getTestClass().getName().replace(".", "/"),
                "-",
                context.getTestMethod().getName());
        // クラス名 ex)/jp/co/ctc_g/jfw/sample/Sample
        String clazz = Strings.join(
                "/",
                context.getTestClass().getName().replace(".", "/"));
        // パッケージ ex)/jp/co/ctc_g/jfw/sample/DatabaseInitialize
        String pakkage = Strings.join(
                "/",
                context.getTestClass().getPackage().getName().replace(".", "/"),
                "/",
                DatabaseInitialize.class.getSimpleName());
        return Arrays.gen(clazzMethod, clazz, pakkage);
    } else {
        return Arrays.gen(config.file());
    }
}
 
Example #5
Source File: ContextCacheTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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);
}
 
Example #6
Source File: WireMockListener.java    From restdocs-wiremock with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
	if(wireMockAnnotation == null) {
		return;
	}
	WireMockTest methodAnnotation = testContext.getTestMethod().getAnnotation(WireMockTest.class);
	
	String stubPath = "";
	if(this.wireMockAnnotation.stubPath() != null) {
		stubPath = this.wireMockAnnotation.stubPath();
	}
	if (methodAnnotation != null && methodAnnotation.stubPath() != null) {
		stubPath += "/" + methodAnnotation.stubPath();
	}

	ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) testContext
			.getApplicationContext();

	WireMockServer server = applicationContext.getBean(WireMockServer.class);
	server.resetMappings();
	if(! stubPath.isEmpty()) {
		server.loadMappingsUsing(new JsonFileMappingsSource(new ClasspathFileSource(stubPath)));
	}
}
 
Example #7
Source File: TestDatabaseKeeper.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
/**
 * SQLファイル検索場所候補にさらにRDBMS方言別の検索候補を追加します。
 * @param candidates SQLファイルの検索場所候補の配列
 * @param context 現在のテスト実行コンテキスト
 * @param config コンフィグ
 * @param source SQL実行対象のデータソース
 * @return RDBMS方言別の検索候補を含む、SQLファイル検索場所候補
 */
protected String[] resolveDialect(
        final String[] candidates,
        TestContext context,
        DatabaseInitialize config,
        DataSource source) {
    final DialectType dialect = DialectType.detect(source);
    if (dialect != null) {
        return Arrays.gen(candidates.length * 2, new GenCall<String>() {
            public String gen(int index, int total) {
                if (index % 2 == 0) {
                    return Strings.join(candidates[index / 2], "_", dialect.name().toLowerCase());
                } else {
                    return candidates[index / 2];
                }
            }
        });
    } else {
        return candidates;
    }
}
 
Example #8
Source File: TransactionalTestExecutionListener.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Determine whether or not to rollback transactions by default for the
 * supplied {@linkplain TestContext test context}.
 * <p>Supports {@link Rollback @Rollback} or {@link Commit @Commit} 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
 */
protected final boolean isDefaultRollback(TestContext testContext) throws Exception {
	Class<?> testClass = testContext.getTestClass();
	Rollback rollback = AnnotatedElementUtils.findMergedAnnotation(testClass, Rollback.class);
	boolean rollbackPresent = (rollback != null);

	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 true;
}
 
Example #9
Source File: ExecutionListenerHelper.java    From flyway-test-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to build test execution information with test class and
 * method
 *
 * @param testContext of spring test environment
 *
 * @return String like &lt;Class Name&gt;[.&lt;Method Name&gt;]
 */
public static String getExecutionInformation(TestContext testContext) {
    String result = "";
    Class<?> testClass = testContext.getTestClass();

    result = testClass.getName();

    // now check for method
    Method m = null;

    try {
        m = testContext.getTestMethod();
    } catch (IllegalStateException ex) {
        // Do Nothing
    }

    if (m != null) {
        result = result + "." + m.getName();
    }

    return result;
}
 
Example #10
Source File: AbstractDirtiesContextTestExecutionListener.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
	}
}
 
Example #11
Source File: TransactionalTestExecutionListener.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #12
Source File: TransactionalTestExecutionListener.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Determine whether or not to rollback transactions for the supplied
 * {@linkplain TestContext test context} by taking into consideration the
 * {@linkplain #isDefaultRollback(TestContext) default rollback} flag and a
 * possible method-level override via the {@link Rollback @Rollback}
 * annotation.
 * @param testContext the test context for which the rollback flag
 * should be retrieved
 * @return the <em>rollback</em> flag for the supplied test context
 * @throws Exception if an error occurs while determining the rollback flag
 */
protected final boolean isRollback(TestContext testContext) throws Exception {
	boolean rollback = isDefaultRollback(testContext);
	Rollback rollbackAnnotation = findAnnotation(testContext.getTestMethod(), Rollback.class);
	if (rollbackAnnotation != null) {
		boolean rollbackOverride = rollbackAnnotation.value();
		if (logger.isDebugEnabled()) {
			logger.debug(String.format(
				"Method-level @Rollback(%s) overrides default rollback [%s] for test context %s.",
				rollbackOverride, rollback, testContext));
		}
		rollback = rollbackOverride;
	}
	else {
		if (logger.isDebugEnabled()) {
			logger.debug(String.format(
				"No method-level @Rollback override: using default rollback [%s] for test context %s.", rollback,
				testContext));
		}
	}
	return rollback;
}
 
Example #13
Source File: TransactionalTestExecutionListener.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #14
Source File: ContextCacheTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #15
Source File: DocmanReaderTestExecutionListener.java    From CogStack-Pipeline with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeTestClass(TestContext testContext) {
    DbmsTestUtils dbTestUtils =
            testContext.getApplicationContext().getBean(DbmsTestUtils.class);
    dbTestUtils.createJobRepository();
    dbTestUtils.createDocManInputTable();
    dbTestUtils.createBasicOutputTable();
    TestUtils testUtils =
            testContext.getApplicationContext().getBean(TestUtils.class);
    Environment env = testContext.getApplicationContext().getBean(Environment.class);
    testUtils.deleteESTestIndexAndSetUpMapping();
    testUtils.insertDataIntoDocmanTable(env.getProperty("tblInputDocs"));
}
 
Example #16
Source File: AbstractDirtiesContextTestExecutionListener.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Perform the actual work for {@link #beforeTestMethod} and {@link #afterTestMethod}
 * by dirtying the context if appropriate (i.e., according to the required modes).
 * @param testContext the test context whose application context should
 * potentially be marked as dirty; never {@code null}
 * @param requiredMethodMode the method mode required for a context to
 * be marked dirty in the current phase; 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 beforeOrAfterTestMethod(TestContext testContext, MethodMode requiredMethodMode,
		ClassMode requiredClassMode) throws Exception {

	Assert.notNull(testContext, "TestContext must not be null");
	Assert.notNull(requiredMethodMode, "requiredMethodMode must not be null");
	Assert.notNull(requiredClassMode, "requiredClassMode must not be null");

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

	DirtiesContext methodAnn = AnnotatedElementUtils.findMergedAnnotation(testMethod, DirtiesContext.class);
	DirtiesContext classAnn = AnnotatedElementUtils.findMergedAnnotation(testClass, DirtiesContext.class);
	boolean methodAnnotated = (methodAnn != null);
	boolean classAnnotated = (classAnn != null);
	MethodMode methodMode = (methodAnnotated ? methodAnn.methodMode() : null);
	ClassMode classMode = (classAnnotated ? classAnn.classMode() : null);

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

	if ((methodMode == requiredMethodMode) || (classMode == requiredClassMode)) {
		HierarchyMode hierarchyMode = (methodAnnotated ? methodAnn.hierarchyMode() : classAnn.hierarchyMode());
		dirtyContext(testContext, hierarchyMode);
	}
}
 
Example #17
Source File: UnitTestDependencyInjectionTestExecutionListener.java    From wisp with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #18
Source File: SqlScriptsTestExecutionListener.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Detect a default SQL script by implementing the algorithm defined in
 * {@link Sql#scripts}.
 */
private String detectDefaultScript(TestContext testContext, boolean classLevel) {
	Class<?> clazz = testContext.getTestClass();
	Method method = testContext.getTestMethod();
	String elementType = (classLevel ? "class" : "method");
	String elementName = (classLevel ? clazz.getName() : method.toString());

	String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName());
	if (!classLevel) {
		resourcePath += "." + method.getName();
	}
	resourcePath += ".sql";

	String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
	ClassPathResource classPathResource = new ClassPathResource(resourcePath);

	if (classPathResource.exists()) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Detected default SQL script \"%s\" for test %s [%s]",
					prefixedResourcePath, elementType, elementName));
		}
		return prefixedResourcePath;
	}
	else {
		String msg = String.format("Could not detect default SQL script for test %s [%s]: " +
				"%s does not exist. Either declare statements or scripts via @Sql or make the " +
				"default SQL script available.", elementType, elementName, classPathResource);
		logger.error(msg);
		throw new IllegalStateException(msg);
	}
}
 
Example #19
Source File: ServletTestExecutionListener.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void setUpRequestContextIfNecessary(TestContext testContext) {
	if (!isActivated(testContext) || alreadyPopulatedRequestContextHolder(testContext)) {
		return;
	}

	ApplicationContext context = testContext.getApplicationContext();

	if (context instanceof WebApplicationContext) {
		WebApplicationContext wac = (WebApplicationContext) context;
		ServletContext servletContext = wac.getServletContext();
		Assert.state(servletContext instanceof MockServletContext, () -> String.format(
					"The WebApplicationContext for test context %s must be configured with a MockServletContext.",
					testContext));

		if (logger.isDebugEnabled()) {
			logger.debug(String.format(
					"Setting up MockHttpServletRequest, MockHttpServletResponse, ServletWebRequest, and RequestContextHolder for test context %s.",
					testContext));
		}

		MockServletContext mockServletContext = (MockServletContext) servletContext;
		MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext);
		request.setAttribute(CREATED_BY_THE_TESTCONTEXT_FRAMEWORK, Boolean.TRUE);
		MockHttpServletResponse response = new MockHttpServletResponse();
		ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);

		RequestContextHolder.setRequestAttributes(servletWebRequest);
		testContext.setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
		testContext.setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);

		if (wac instanceof ConfigurableApplicationContext) {
			@SuppressWarnings("resource")
			ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) wac;
			ConfigurableListableBeanFactory bf = configurableApplicationContext.getBeanFactory();
			bf.registerResolvableDependency(MockHttpServletResponse.class, response);
			bf.registerResolvableDependency(ServletWebRequest.class, servletWebRequest);
		}
	}
}
 
Example #20
Source File: SqlScriptsTestExecutionListener.java    From java-technology-stack with MIT License 5 votes vote down vote up
private String[] getScripts(Sql sql, TestContext testContext, boolean classLevel) {
	String[] scripts = sql.scripts();
	if (ObjectUtils.isEmpty(scripts) && ObjectUtils.isEmpty(sql.statements())) {
		scripts = new String[] {detectDefaultScript(testContext, classLevel)};
	}
	return scripts;
}
 
Example #21
Source File: WireMockListener.java    From restdocs-wiremock with Apache License 2.0 5 votes vote down vote up
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
	if(wireMockAnnotation == null) {
		return;
	}
	ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) testContext
			.getApplicationContext();

	applicationContext.getBean(WireMockServer.class).resetToDefaultMappings();
}
 
Example #22
Source File: FlywayTestExecutionListener.java    From flyway-test-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * Invoke this method before test class will be created.</p>
 *
 * <b>Attention:</b> This will be only invoked if spring version &gt;= 3.x
 * are used.
 *
 * @param testContext
 *            default test context filled from spring
 *
 * @throws Exception
 *             if any error occurred
 */
public void beforeTestClass(final TestContext testContext) throws Exception {
    // no we check for the DBResetForClass
    final Class<?> testClass = testContext.getTestClass();

    handleFlywayTestAnnotationForClass(testContext, testClass);

    // now detect if current class has a beforeClass or BeforeAllAnnotation
    Class beforeClassClass = getClassOrNullForName("org.junit.BeforeClass");
    Class beforeAllClass = getClassOrNullForName("org.junit.jupiter.api.BeforeAll");
    Class beforeClassTestNgClass = getClassOrNullForName("org.testng.annotations.BeforeClass");

    // contains first finding of FlywayTest annotation together with a Before annotation
    handleFlywayTestWithTestAnnotation(testContext, testClass, beforeClassClass, beforeAllClass, beforeClassTestNgClass);
}
 
Example #23
Source File: TestDatabaseKeeper.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * データベースを初期化します。
 * @param context 現在のテスト実行コンテキスト
 * @param config コンフィグ
 */
protected void initializeDatabase(TestContext context, DatabaseInitialize config) {
    String[] candidates = createFileLocationCandidates(context, config);
    DataSource source = findDataSource(context, config);
    String[] resolved = resolveDialect(candidates, context, config, source);
    String content = readSqlFile(resolved, context, config);
    String[] executables = createExecutables(content);
    execute(executables, source, context);
}
 
Example #24
Source File: CleanTestExecutionListener.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
public void afterTestClass(TestContext testContext) throws Exception {
  RepositoryService repositoryService = testContext.getApplicationContext().getBean(RepositoryService.class);
  for (Deployment deployment : repositoryService.createDeploymentQuery().list()) {
    repositoryService.deleteDeployment(deployment.getId(), true);
  }
}
 
Example #25
Source File: WireMockListener.java    From restdocs-wiremock with Apache License 2.0 5 votes vote down vote up
@Override
public void afterTestClass(TestContext testContext) throws Exception {
	if(wireMockAnnotation == null) {
		return;
	}
	ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) testContext
			.getApplicationContext();

	applicationContext.getBean(WireMockServer.class).stop();
}
 
Example #26
Source File: WireMockTestExecutionListener.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
	if (applicationContextBroken(testContext)
			|| wireMockConfigurationMissing(testContext)
			|| annotationMissing(testContext)) {
		return;
	}
	WireMockConfiguration wireMockConfiguration = wireMockConfig(testContext);
	if (wireMockConfiguration.wireMock.isResetMappingsAfterEachTest()) {
		if (log.isDebugEnabled()) {
			log.debug("Resetting mappings for the next test.");
		}
		wireMockConfiguration.resetMappings();
	}
}
 
Example #27
Source File: BasicTestExecutionListenerLargeInsert.java    From CogStack-Pipeline with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeTestClass(TestContext testContext) {
    DbmsTestUtils dbTestUtils =
            testContext.getApplicationContext().getBean(DbmsTestUtils.class);
    dbTestUtils.createJobRepository();
    dbTestUtils.createBasicInputTable();
    dbTestUtils.createBasicOutputTable();
    TestUtils testUtils =
            testContext.getApplicationContext().getBean(TestUtils.class);
    Environment env = testContext.getApplicationContext().getBean(Environment.class);
    testUtils.deleteESTestIndexAndSetUpMapping();
    testUtils.insertDataIntoBasicTable(env.getProperty("tblInputDocs"),true,1,75,false);
}
 
Example #28
Source File: ContextCacheTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void removeContextHierarchyCacheLevel3Then2() {

	// 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 3-A
	contextCache.remove(getMergedContextConfiguration(testContext3a), HierarchyMode.CURRENT_LEVEL);
	assertContextCacheStatistics(contextCache, "removed level 3-A", 3, 1, 4);
	assertParentContextCount(2);

	// Remove Level 2
	// Should also remove Level 3-B, leaving only Level 1.
	contextCache.remove(getMergedContextConfiguration(testContext3b).getParent(), HierarchyMode.CURRENT_LEVEL);
	assertContextCacheStatistics(contextCache, "removed level 2", 1, 1, 4);
	assertParentContextCount(0);
}
 
Example #29
Source File: TikaTestExecutionListener.java    From CogStack-Pipeline with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeTestClass(TestContext testContext) {
    DbmsTestUtils dbTestUtils =
            testContext.getApplicationContext().getBean(DbmsTestUtils.class);
    dbTestUtils.createJobRepository();
    dbTestUtils.createTikaTable();
    dbTestUtils.createBasicOutputTable();
    TestUtils testUtils =
            testContext.getApplicationContext().getBean(TestUtils.class);
    Environment env = testContext.getApplicationContext().getBean(Environment.class);
    testUtils.deleteESTestIndexAndSetUpMapping();
    testUtils.insertTestBinariesForTika("tblInputDocs");

}
 
Example #30
Source File: JAXRSServerExecutionListener.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
    JAXRSServerFactoryBean factory = testContext.getApplicationContext().getBean(JAXRSServerFactoryBean.class);
    String basePath = testContext.getApplicationContext().getEnvironment()
            .getProperty("basePath", "http://localhost:9080/api/");
    logger.debug("Creating JAX-RS Server for resource {} under {} ", testContext.getTestClass(), basePath);
    factory.setBindingId(JAXRSBindingFactory.JAXRS_BINDING_ID);
    factory.setAddress(basePath);
    server = factory.create();
}