Skip to content

Introduce autowiring support for the current TestContext [SPR-8299] #12947

Closed

Description

@spring-projects-issues

Sam Brannen opened SPR-8299 and commented

Status Quo

Tests currently do not have access to the current TestContext.

Providing access to the TestContext would allow programmatic access to TestContext properties as well as methods such as markApplicationContextDirty().

Considerations

Instead of exposing the TestContext as is, it may be preferential to expose a new (yet-to-be-implemented) public-facing interface that defines a subset of the publicly available methods in TestContext.

A similar approach could be introduced to provide programmatic support for transaction management.

Code Samples

DependencyInjectionTestExecutionListener's injectDependencies(TestContext) method could be modified as follows:

protected void injectDependencies(final TestContext testContext) throws Exception {
	Object bean = testContext.getTestInstance();
	ApplicationContext applicationContext = testContext.getApplicationContext();

	// BEGIN NEW CODE
	// Enable autowiring of the current TestContext.
	if (applicationContext instanceof ConfigurableApplicationContext) {
		ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
		configurableApplicationContext.getBeanFactory().registerResolvableDependency(TestContext.class, testContext);
	}
	// END NEW CODE

	AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
	beanFactory.autowireBeanProperties(bean, AutowireCapableBeanFactory.AUTOWIRE_NO, false);
	beanFactory.initializeBean(bean, testContext.getTestClass().getName());
	testContext.removeAttribute(REINJECT_DEPENDENCIES_ATTRIBUTE);
}
public class MyTests {

	@Autowired
	protected TestContext testContext;

	@Test
	public void test() {
		assertNotNull(testContext);
		assertEquals("test", testContext.getTestMethod().getName());
	}
}

Affects: 2.5.6

Issue Links:

Activity

  1. added
    in: test
    type: enhancement
    on Jan 11, 2019
  2. self-assigned this
    on Jan 15, 2019
  3. removed this from the General Backlog milestone on Feb 23, 2019
  4. sbrannen commented on Feb 23, 2019

    @sbrannen
    Member

    Closing this issue due to lack of interest from the community.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

in: testtype: enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions