本文整理匯總了Java中org.springframework.test.context.TestContext類的典型用法代碼示例。如果您正苦於以下問題:Java TestContext類的具體用法?Java TestContext怎麽用?Java TestContext使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
TestContext類屬於org.springframework.test.context包,在下文中一共展示了TestContext類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: optimizedDbReset
import org.springframework.test.context.TestContext; //導入依賴的package包/類
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);
}
開發者ID:zonkyio,項目名稱:embedded-database-spring-test,代碼行數:21,代碼來源:OptimizedFlywayTestExecutionListener.java
示例2: prepareFailingTestInstanceShouldPrintReport
import org.springframework.test.context.TestContext; //導入依賴的package包/類
@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"));
}
開發者ID:vikrammane23,項目名稱:https-github.com-g0t4-jenkins2-course-spring-boot,代碼行數:19,代碼來源:AutoConfigureReportTestExecutionListenerTests.java
示例3: afterTestMethod
import org.springframework.test.context.TestContext; //導入依賴的package包/類
@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);
}
示例4: afterTestMethod
import org.springframework.test.context.TestContext; //導入依賴的package包/類
@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();
}
示例5: afterTestMethod
import org.springframework.test.context.TestContext; //導入依賴的package包/類
@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();
}
示例6: initDatabase
import org.springframework.test.context.TestContext; //導入依賴的package包/類
/**
* 初始化數據源
*
* @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);
}
}
示例7: resetMocks
import org.springframework.test.context.TestContext; //導入依賴的package包/類
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);
}
}
}
}
示例8: should_reset_only_mocks_and_spies
import org.springframework.test.context.TestContext; //導入依賴的package包/類
@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);
}
示例9: should_never_reset_mock
import org.springframework.test.context.TestContext; //導入依賴的package包/類
@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);
}
示例10: beforeTestMethod
import org.springframework.test.context.TestContext; //導入依賴的package包/類
@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);
}
示例11: beforeTestClass
import org.springframework.test.context.TestContext; //導入依賴的package包/類
@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]));
}
示例12: getTransactionManager
import org.springframework.test.context.TestContext; //導入依賴的package包/類
/**
* 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);
}
示例13: isDefaultRollback
import org.springframework.test.context.TestContext; //導入依賴的package包/類
/**
* 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();
}
示例14: retrieveConfigurationAttributes
import org.springframework.test.context.TestContext; //導入依賴的package包/類
/**
* 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;
}
示例15: executeSqlScripts
import org.springframework.test.context.TestContext; //導入依賴的package包/類
/**
* 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);
}
}