下面列出了怎么用org.springframework.test.context.TestContextManager的API类实例代码及写法,或者点击链接到github查看源代码。
@Test(expected = Exception.class)
public void checkThatExceptionsAreNotSilentlySwallowed() throws Exception {
SpringJUnit4ClassRunner runner = new SpringJUnit4ClassRunner(getClass()) {
@Override
protected TestContextManager createTestContextManager(Class<?> clazz) {
return new TestContextManager(clazz) {
@Override
public void prepareTestInstance(Object testInstance) {
throw new RuntimeException(
"This RuntimeException should be caught and wrapped in an Exception.");
}
};
}
};
runner.createTest();
}
@Before
public void setUp() throws Exception {
this.testContextManager = new TestContextManager( getClass() );
this.testContextManager.prepareTestInstance( this );
KettleEnvironment.init();
PentahoSessionHolder.setStrategyName( PentahoSessionHolder.MODE_GLOBAL );
mockVersionManager();
removePentahoRootFolder();
startMicroPlatform();
createSystemUser();
createTester();
createPurRepository();
loginAsTester();
}
@Test(expected = Exception.class)
public void checkThatExceptionsAreNotSilentlySwallowed() throws Exception {
SpringJUnit4ClassRunner runner = new SpringJUnit4ClassRunner(getClass()) {
@Override
protected TestContextManager createTestContextManager(Class<?> clazz) {
return new TestContextManager(clazz) {
@Override
public void prepareTestInstance(Object testInstance) {
throw new RuntimeException(
"This RuntimeException should be caught and wrapped in an Exception.");
}
};
}
};
runner.createTest();
}
@Test(expected = Exception.class)
public void checkThatExceptionsAreNotSilentlySwallowed() throws Exception {
SpringJUnit4ClassRunner runner = new SpringJUnit4ClassRunner(getClass()) {
@Override
protected TestContextManager createTestContextManager(Class<?> clazz) {
return new TestContextManager(clazz) {
@Override
public void prepareTestInstance(Object testInstance) {
throw new RuntimeException(
"This RuntimeException should be caught and wrapped in an Exception.");
}
};
}
};
runner.createTest();
}
/**
* Wrap the supplied {@link Statement} with a {@code RunBeforeTestMethodCallbacks} statement.
* @see RunBeforeTestMethodCallbacks
*/
private Statement withBeforeTestMethodCallbacks(Statement next, Method testMethod,
Object testInstance, TestContextManager testContextManager) {
return new RunBeforeTestMethodCallbacks(
next, testInstance, testMethod, testContextManager);
}
/**
* Wrap the supplied {@link Statement} with a {@code RunAfterTestMethodCallbacks} statement.
* @see RunAfterTestMethodCallbacks
*/
private Statement withAfterTestMethodCallbacks(Statement next, Method testMethod,
Object testInstance, TestContextManager testContextManager) {
return new RunAfterTestMethodCallbacks(
next, testInstance, testMethod, testContextManager);
}
private ExtensionContext buildExtensionContext(String methodName) {
Class<?> testClass = SpringTestCase.class;
Method method = ReflectionUtils.findMethod(getClass(), methodName);
Store store = mock(Store.class);
given(store.getOrComputeIfAbsent(any(), any(), any())).willReturn(new TestContextManager(testClass));
ExtensionContext extensionContext = mock(ExtensionContext.class);
given(extensionContext.getTestClass()).willReturn(Optional.of(testClass));
given(extensionContext.getElement()).willReturn(Optional.of(method));
given(extensionContext.getStore(any())).willReturn(store);
return extensionContext;
}
/**
* Get the {@link TestContextManager} associated with the supplied {@code ExtensionContext}.
* @return the {@code TestContextManager} (never {@code null})
*/
private static TestContextManager getTestContextManager(ExtensionContext context) {
Assert.notNull(context, "ExtensionContext must not be null");
Class<?> testClass = context.getRequiredTestClass();
Store store = getStore(context);
return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);
}
/**
* Wrap the supplied {@link Statement} with a {@code RunBeforeTestMethodCallbacks} statement.
* @see RunBeforeTestMethodCallbacks
*/
private Statement withBeforeTestMethodCallbacks(Statement next, Method testMethod,
Object testInstance, TestContextManager testContextManager) {
return new RunBeforeTestMethodCallbacks(
next, testInstance, testMethod, testContextManager);
}
/**
* Wrap the supplied {@link Statement} with a {@code RunAfterTestMethodCallbacks} statement.
* @see RunAfterTestMethodCallbacks
*/
private Statement withAfterTestMethodCallbacks(Statement next, Method testMethod,
Object testInstance, TestContextManager testContextManager) {
return new RunAfterTestMethodCallbacks(
next, testInstance, testMethod, testContextManager);
}
public SpringProcessEngineTestCase() {
super();
this.testContextManager = new TestContextManager(getClass());
SpringTestHelper testHelper = lookupTestHelper();
testHelper.beforeTestClass(testContextManager);
}
private ExtensionContext buildExtensionContext(String methodName) {
Class<?> testClass = SpringTestCase.class;
Method method = ReflectionUtils.findMethod(getClass(), methodName);
Store store = mock(Store.class);
when(store.getOrComputeIfAbsent(any(), any(), any())).thenReturn(new TestContextManager(testClass));
ExtensionContext extensionContext = mock(ExtensionContext.class);
when(extensionContext.getTestClass()).thenReturn(Optional.of(testClass));
when(extensionContext.getElement()).thenReturn(Optional.of(method));
when(extensionContext.getStore(any())).thenReturn(store);
return extensionContext;
}
/**
* Wrap the supplied {@link Statement} with a {@code RunBeforeTestMethodCallbacks} statement.
* @see RunBeforeTestMethodCallbacks
*/
private Statement withBeforeTestMethodCallbacks(Statement statement, FrameworkMethod frameworkMethod,
Object testInstance, TestContextManager testContextManager) {
return new RunBeforeTestMethodCallbacks(
statement, testInstance, frameworkMethod.getMethod(), testContextManager);
}
/**
* Wrap the supplied {@link Statement} with a {@code RunAfterTestMethodCallbacks} statement.
* @see RunAfterTestMethodCallbacks
*/
private Statement withAfterTestMethodCallbacks(Statement statement, FrameworkMethod frameworkMethod,
Object testInstance, TestContextManager testContextManager) {
return new RunAfterTestMethodCallbacks(
statement, testInstance, frameworkMethod.getMethod(), testContextManager);
}
/**
* Get the {@link TestContextManager} associated with the supplied {@code ExtensionContext}.
* @return the {@code TestContextManager} (never {@code null})
*/
private static TestContextManager getTestContextManager(ExtensionContext context) {
Assert.notNull(context, "ExtensionContext must not be null");
Class<?> testClass = context.getRequiredTestClass();
Store store = getStore(context);
return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);
}
private TestContextManager getTestContextManager(ExtensionContext context) {
Assert.notNull(context, "ExtensionContext must not be null");
Class<?> testClass = context.getTestClass()
.get();
ExtensionContext.Store store = context.getStore(namespace);
return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);
}
@Before
public void setup() throws Exception {
this.testContextManager = new TestContextManager(getClass());
this.testContextManager.prepareTestInstance(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
/**
* Get the {@link TestContextManager} associated with the supplied {@code ExtensionContext}.
*
* @return the {@code TestContextManager} (never {@code null})
*/
private static TestContextManager getTestContextManager(ExtensionContext context) {
Assert.notNull(context, "ExtensionContext must not be null");
Class<?> testClass = context.getRequiredTestClass();
ExtensionContext.Store store = getStore(context);
return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);
}
@Before
public void setUp() throws Exception {
this.testContextManager = new TestContextManager( getClass() );
this.testContextManager.prepareTestInstance( this );
IRepositoryVersionManager mockRepositoryVersionManager = mock( IRepositoryVersionManager.class );
when( mockRepositoryVersionManager.isVersioningEnabled( anyString() ) ).thenReturn( true );
when( mockRepositoryVersionManager.isVersionCommentEnabled( anyString() ) ).thenReturn( false );
JcrRepositoryFileUtils.setRepositoryVersionManager( mockRepositoryVersionManager );
loginAsRepositoryAdmin();
SimpleJcrTestUtils.deleteItem( testJcrTemplate, ServerRepositoryPaths.getPentahoRootFolderPath() );
mp = new MicroPlatform();
// used by DefaultPentahoJackrabbitAccessControlHelper
mp.defineInstance( "tenantedUserNameUtils", userNameUtils );
mp.defineInstance( "tenantedRoleNameUtils", roleNameUtils );
mp.defineInstance( IAuthorizationPolicy.class, authorizationPolicy );
mp.defineInstance( ITenantManager.class, tenantManager );
mp.defineInstance( "roleAuthorizationPolicyRoleBindingDaoTarget", roleBindingDaoTarget );
mp.defineInstance( "repositoryAdminUsername", repositoryAdminUsername );
mp.defineInstance( "RepositoryFileProxyFactory",
new RepositoryFileProxyFactory( testJcrTemplate, repositoryFileDao ) );
mp.defineInstance( "useMultiByteEncoding", new Boolean( false ) );
// Start the micro-platform
mp.start();
loginAsRepositoryAdmin();
setAclManagement();
systemTenant =
tenantManager.createTenant( null, ServerRepositoryPaths.getPentahoRootFolderName(), singleTenantAdminRoleName,
tenantAuthenticatedRoleName, "Anonymous" );
userRoleDao.createUser( systemTenant, sysAdminUserName, "password", "", new String[] { singleTenantAdminRoleName } );
logout();
super.setUp();
KettleEnvironment.init();
// programmatically register plugins, annotation based plugins do not get loaded unless
// they are in kettle's plugins folder.
JobEntryPluginType.getInstance().registerCustom( JobEntryAttributeTesterJobEntry.class, "test",
"JobEntryAttributeTester", "JobEntryAttributeTester", "JobEntryAttributeTester", "" );
StepPluginType.getInstance().registerCustom( TransStepAttributeTesterTransStep.class, "test",
"StepAttributeTester", "StepAttributeTester", "StepAttributeTester", "" );
repositoryMeta = new PurRepositoryMeta();
repositoryMeta.setName( "JackRabbit" );
repositoryMeta.setDescription( "JackRabbit test repository" );
userInfo = new UserInfo( EXP_LOGIN, "password", EXP_USERNAME, "Apache Tomcat user", true );
repository = new PurRepository();
repository.init( repositoryMeta );
login( sysAdminUserName, systemTenant, new String[] { singleTenantAdminRoleName, tenantAuthenticatedRoleName } );
ITenant tenantAcme =
tenantManager.createTenant( systemTenant, EXP_TENANT, singleTenantAdminRoleName, tenantAuthenticatedRoleName,
"Anonymous" );
userRoleDao.createUser( tenantAcme, EXP_LOGIN, "password", "", new String[] { singleTenantAdminRoleName } );
logout();
setUpUser();
PurRepository purRep = (PurRepository) repository;
purRep.setPurRepositoryConnector( new PurRepositoryConnector( purRep, (PurRepositoryMeta) repositoryMeta, purRep
.getRootRef() ) );
( (PurRepository) repository ).setTest( repo );
repository.connect( EXP_LOGIN, "password" );
login( EXP_LOGIN, tenantAcme, new String[] { singleTenantAdminRoleName, tenantAuthenticatedRoleName } );
System.out.println( "PUR NAME!!!: " + repo.getClass().getCanonicalName() );
RepositoryFile repositoryFile = repo.getFile( ClientRepositoryPaths.getPublicFolderPath() );
Serializable repositoryFileId = repositoryFile.getId();
List<RepositoryFile> files = repo.getChildren( repositoryFileId );
StringBuilder buf = new StringBuilder();
for ( RepositoryFile file : files ) {
buf.append( "\n" ).append( file );
}
assertTrue( "files not deleted: " + buf, files.isEmpty() );
}
/**
* Get the {@link TestContextManager} associated with this runner.
*/
protected final TestContextManager getTestContextManager() {
return this.testContextManager;
}
/**
* Apply <em>class-level</em> features of the <em>Spring TestContext
* Framework</em> to the supplied {@code base} statement.
* <p>Specifically, this method retrieves the {@link TestContextManager}
* used by this rule and its associated {@link SpringMethodRule} and
* invokes the {@link TestContextManager#beforeTestClass() beforeTestClass()}
* and {@link TestContextManager#afterTestClass() afterTestClass()} methods
* on the {@code TestContextManager}.
* <p>In addition, this method checks whether the test is enabled in
* the current execution environment. This prevents classes with a
* non-matching {@code @IfProfileValue} annotation from running altogether,
* even skipping the execution of {@code beforeTestClass()} methods
* in {@code TestExecutionListeners}.
* @param base the base {@code Statement} that this rule should be applied to
* @param description a {@code Description} of the current test execution
* @return a statement that wraps the supplied {@code base} with class-level
* features of the Spring TestContext Framework
* @see #getTestContextManager
* @see #withBeforeTestClassCallbacks
* @see #withAfterTestClassCallbacks
* @see #withProfileValueCheck
* @see #withTestContextManagerCacheEviction
*/
@Override
public Statement apply(Statement base, Description description) {
Class<?> testClass = description.getTestClass();
if (logger.isDebugEnabled()) {
logger.debug("Applying SpringClassRule to test class [" + testClass.getName() + "]");
}
TestContextManager testContextManager = getTestContextManager(testClass);
Statement statement = base;
statement = withBeforeTestClassCallbacks(statement, testContextManager);
statement = withAfterTestClassCallbacks(statement, testContextManager);
statement = withProfileValueCheck(statement, testClass);
statement = withTestContextManagerCacheEviction(statement, testClass);
return statement;
}
/**
* Get the {@link TestContextManager} associated with the supplied test class.
* @param testClass the test class to be managed; never {@code null}
*/
static TestContextManager getTestContextManager(Class<?> testClass) {
Assert.notNull(testClass, "Test Class must not be null");
return testContextManagerCache.computeIfAbsent(testClass, TestContextManager::new);
}
/**
* Apply <em>instance-level</em> and <em>method-level</em> features of
* the <em>Spring TestContext Framework</em> to the supplied {@code base}
* statement.
* <p>Specifically, this method invokes the
* {@link TestContextManager#prepareTestInstance prepareTestInstance()},
* {@link TestContextManager#beforeTestMethod beforeTestMethod()}, and
* {@link TestContextManager#afterTestMethod afterTestMethod()} methods
* on the {@code TestContextManager}, potentially with Spring timeouts
* and repetitions.
* <p>In addition, this method checks whether the test is enabled in
* the current execution environment. This prevents methods with a
* non-matching {@code @IfProfileValue} annotation from running altogether,
* even skipping the execution of {@code prepareTestInstance()} methods
* in {@code TestExecutionListeners}.
* @param base the base {@code Statement} that this rule should be applied to
* @param frameworkMethod the method which is about to be invoked on the test instance
* @param testInstance the current test instance
* @return a statement that wraps the supplied {@code base} with instance-level
* and method-level features of the Spring TestContext Framework
* @see #withBeforeTestMethodCallbacks
* @see #withAfterTestMethodCallbacks
* @see #withPotentialRepeat
* @see #withPotentialTimeout
* @see #withTestInstancePreparation
* @see #withProfileValueCheck
*/
@Override
public Statement apply(Statement base, FrameworkMethod frameworkMethod, Object testInstance) {
Method testMethod = frameworkMethod.getMethod();
if (logger.isDebugEnabled()) {
logger.debug("Applying SpringMethodRule to test method [" + testMethod + "]");
}
Class<?> testClass = testInstance.getClass();
TestContextManager testContextManager = SpringClassRule.getTestContextManager(testClass);
Statement statement = base;
statement = withBeforeTestMethodCallbacks(statement, testMethod, testInstance, testContextManager);
statement = withAfterTestMethodCallbacks(statement, testMethod, testInstance, testContextManager);
statement = withTestInstancePreparation(statement, testInstance, testContextManager);
statement = withPotentialRepeat(statement, testMethod, testInstance);
statement = withPotentialTimeout(statement, testMethod, testInstance);
statement = withProfileValueCheck(statement, testMethod, testInstance);
return statement;
}
/**
* Wrap the supplied {@link Statement} with a {@code RunPrepareTestInstanceCallbacks} statement.
* @see RunPrepareTestInstanceCallbacks
*/
private Statement withTestInstancePreparation(
Statement next, Object testInstance, TestContextManager testContextManager) {
return new RunPrepareTestInstanceCallbacks(next, testInstance, testContextManager);
}
@Before
public void setUp() throws Exception {
this.testContextManager = new TestContextManager( getClass() );
this.testContextManager.prepareTestInstance( this );
loginAsRepositoryAdmin();
SimpleJcrTestUtils.deleteItem( testJcrTemplate, ServerRepositoryPaths.getPentahoRootFolderPath() );
mp = new MicroPlatform();
// used by DefaultPentahoJackrabbitAccessControlHelper
mp.defineInstance( "tenantedUserNameUtils", userNameUtils );
mp.defineInstance( "tenantedRoleNameUtils", roleNameUtils );
mp.defineInstance( IAuthorizationPolicy.class, authorizationPolicy );
mp.defineInstance( ITenantManager.class, tenantManager );
mp.defineInstance( "roleAuthorizationPolicyRoleBindingDaoTarget", roleBindingDaoTarget );
mp.defineInstance( "repositoryAdminUsername", repositoryAdminUsername );
mp.defineInstance( "RepositoryFileProxyFactory",
new RepositoryFileProxyFactory( testJcrTemplate, repositoryFileDao ) );
mp.defineInstance( "useMultiByteEncoding", new Boolean( false ) );
mp.defineInstance( IAclService.class, new Boolean( false ) );
// Start the micro-platform
mp.start();
loginAsRepositoryAdmin();
setAclManagement();
systemTenant =
tenantManager.createTenant( null, ServerRepositoryPaths.getPentahoRootFolderName(), singleTenantAdminRoleName,
tenantAuthenticatedRoleName, "Anonymous" );
userRoleDao.createUser( systemTenant, sysAdminUserName, "password", "", new String[] { singleTenantAdminRoleName } );
logout();
super.setUp();
KettleEnvironment.init();
// programmatically register plugins, annotation based plugins do not get loaded unless
// they are in kettle's plugins folder.
JobEntryPluginType.getInstance().registerCustom( JobEntryAttributeTesterJobEntry.class, "test",
"JobEntryAttributeTester", "JobEntryAttributeTester", "JobEntryAttributeTester", "" );
StepPluginType.getInstance().registerCustom( TransStepAttributeTesterTransStep.class, "test",
"StepAttributeTester", "StepAttributeTester", "StepAttributeTester", "" );
repositoryMeta = new PurRepositoryMeta();
repositoryMeta.setName( "JackRabbit" );
repositoryMeta.setDescription( "JackRabbit test repository" );
userInfo = new UserInfo( EXP_LOGIN, "password", EXP_USERNAME, "Apache Tomcat user", true );
repository = new PurRepository();
repository.init( repositoryMeta );
login( sysAdminUserName, systemTenant, new String[] { singleTenantAdminRoleName, tenantAuthenticatedRoleName } );
ITenant tenantAcme =
tenantManager.createTenant( systemTenant, EXP_TENANT, singleTenantAdminRoleName, tenantAuthenticatedRoleName,
"Anonymous" );
userRoleDao.createUser( tenantAcme, EXP_LOGIN, "password", "", new String[] { singleTenantAdminRoleName } );
logout();
setUpUser();
PurRepository purRep = (PurRepository) repository;
final PurRepositoryConnector purRepositoryConnector =
new PurRepositoryConnector( purRep, (PurRepositoryMeta) repositoryMeta, purRep.getRootRef() );
purRep.setPurRepositoryConnector( purRepositoryConnector );
purRep.setTest( repo );
repository.connect( EXP_LOGIN, "password" );
login( EXP_LOGIN, tenantAcme, new String[] { singleTenantAdminRoleName, tenantAuthenticatedRoleName } );
System.out.println( "PUR NAME!!!: " + repo.getClass().getCanonicalName() );
RepositoryFile repositoryFile = repo.getFile( ClientRepositoryPaths.getPublicFolderPath() );
Serializable repositoryFileId = repositoryFile.getId();
List<RepositoryFile> files = repo.getChildren( repositoryFileId );
StringBuilder buf = new StringBuilder();
for ( RepositoryFile file : files ) {
buf.append( "\n" ).append( file );
}
assertTrue( "files not deleted: " + buf, files.isEmpty() );
}
@Before
public void setUp() throws Exception {
if (useContextManager())
new TestContextManager(getClass()).prepareTestInstance(this);
}
/**
* Get the {@link TestContextManager} associated with this runner.
*/
protected final TestContextManager getTestContextManager() {
return this.testContextManager;
}
/**
* Get the {@link TestContextManager} associated with this runner.
*/
protected final TestContextManager getTestContextManager() {
return this.testContextManager;
}
/**
* Apply <em>class-level</em> features of the <em>Spring TestContext
* Framework</em> to the supplied {@code base} statement.
* <p>Specifically, this method retrieves the {@link TestContextManager}
* used by this rule and its associated {@link SpringMethodRule} and
* invokes the {@link TestContextManager#beforeTestClass() beforeTestClass()}
* and {@link TestContextManager#afterTestClass() afterTestClass()} methods
* on the {@code TestContextManager}.
* <p>In addition, this method checks whether the test is enabled in
* the current execution environment. This prevents classes with a
* non-matching {@code @IfProfileValue} annotation from running altogether,
* even skipping the execution of {@code beforeTestClass()} methods
* in {@code TestExecutionListeners}.
* @param base the base {@code Statement} that this rule should be applied to
* @param description a {@code Description} of the current test execution
* @return a statement that wraps the supplied {@code base} with class-level
* features of the Spring TestContext Framework
* @see #getTestContextManager
* @see #withBeforeTestClassCallbacks
* @see #withAfterTestClassCallbacks
* @see #withProfileValueCheck
* @see #withTestContextManagerCacheEviction
*/
@Override
public Statement apply(Statement base, Description description) {
Class<?> testClass = description.getTestClass();
if (logger.isDebugEnabled()) {
logger.debug("Applying SpringClassRule to test class [" + testClass.getName() + "]");
}
TestContextManager testContextManager = getTestContextManager(testClass);
Statement statement = base;
statement = withBeforeTestClassCallbacks(statement, testContextManager);
statement = withAfterTestClassCallbacks(statement, testContextManager);
statement = withProfileValueCheck(statement, testClass);
statement = withTestContextManagerCacheEviction(statement, testClass);
return statement;
}
/**
* Get the {@link TestContextManager} associated with the supplied test class.
* @param testClass the test class to be managed; never {@code null}
*/
static TestContextManager getTestContextManager(Class<?> testClass) {
Assert.notNull(testClass, "Test Class must not be null");
return testContextManagerCache.computeIfAbsent(testClass, TestContextManager::new);
}