Support automatic constructor injection in JUnit Jupiter

Prior to this commit, dependency injection of all arguments in a test
class constructor invoked by JUnit Jupiter was only possible if the
constructor was explicitly annotated with @Autowired.

This commit introduces support for a configurable "test constructor
autowire" mode which defaults to false in order to remain backwards
compatible.

Specifically, this mode can be configured globally for an entire test
suite via a new "spring.test.constructor.autowire" JVM system property
that can alternatively be configured via the SpringProperties
mechanism. In addition, the global "test constructor autowire" mode can
be overridden locally on a per-class basis via the new @TestConstructor
annotation.

Closes gh-22286
This commit is contained in:
Sam Brannen 2019-05-06 19:34:50 +02:00
parent eb16e853b1
commit 77eef47483
5 changed files with 402 additions and 14 deletions

View File

@ -0,0 +1,94 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* {@code @TestConstructor} is a type-level annotation that is used to configure
* whether a test class constructor should be automatically autowired from
* components in the test's {@link org.springframework.context.ApplicationContext
* ApplicationContext}.
*
* <p>If {@code @TestConstructor} is not <em>present</em> or <em>meta-present</em>
* on a test class, the default <em>test constructor autowire</em> mode will be used.
* See {@link #AUTOWIRE_TEST_CONSTRUCTOR_PROPERTY_NAME} for details on how to change
* the default mode. Note, however, that a local declaration of
* {@link org.springframework.beans.factory.annotation.Autowired @Autowired} on
* a constructor takes precedence over both {@code @TestConstructor} and the default
* mode.
*
* <p>This annotation may be used as a <em>meta-annotation</em> to create custom
* <em>composed annotations</em>.
*
* <p>As of Spring Framework 5.2, this annotation is only supported in conjunction with
* the {@link org.springframework.test.context.junit.jupiter.SpringExtension
* SpringExtension} for use with JUnit Jupiter. Note that the {@code SpringExtension} is
* often automatically registered for you &mdash; for example, when using annotations such as
* {@link org.springframework.test.context.junit.jupiter.SpringJUnitConfig @SpringJUnitConfig} and
* {@link org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig @SpringJUnitWebConfig}
* or various test-related annotations from Spring Boot Test.
*
* @author Sam Brannen
* @since 5.2
* @see org.springframework.beans.factory.annotation.Autowired @Autowired
* @see org.springframework.test.context.junit.jupiter.SpringExtension SpringExtension
* @see org.springframework.test.context.junit.jupiter.SpringJUnitConfig @SpringJUnitConfig
* @see org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig @SpringJUnitWebConfig
* @see ContextConfiguration @ContextConfiguration
* @see ContextHierarchy @ContextHierarchy
* @see ActiveProfiles @ActiveProfiles
* @see TestPropertySource @TestPropertySource
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface TestConstructor {
/**
* System property used to configure the default <em>test constructor autowire</em>
* mode: {@value #TEST_CONSTRUCTOR_AUTOWIRE_PROPERTY_NAME}.
* <p>May alternatively be configured via the
* {@link org.springframework.core.SpringProperties SpringProperties} mechanism.
* <p>If the property is not set, test class constructors will not be automatically
* autowired.
* @see #autowire
*/
String TEST_CONSTRUCTOR_AUTOWIRE_PROPERTY_NAME = "spring.test.constructor.autowire";
/**
* Flag for setting the <em>test constructor autowire</em> mode for the
* current test class.
* <p>Setting this flag overrides the global default. See
* {@link #AUTOWIRE_TEST_CONSTRUCTOR_PROPERTY_NAME} for details on how to
* change the global default.
* @return {@code true} if all test constructor arguments should be autowired
* from the test's {@link org.springframework.context.ApplicationContext
* ApplicationContext}
* @see #AUTOWIRE_TEST_CONSTRUCTOR_PROPERTY_NAME
* @see org.springframework.beans.factory.annotation.Autowired @Autowired
*/
boolean autowire();
}

View File

@ -34,12 +34,12 @@ import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.TestInstancePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.ParameterResolutionDelegate;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.lang.Nullable;
import org.springframework.test.context.TestConstructor;
import org.springframework.test.context.TestContextManager;
import org.springframework.test.context.support.TestConstructorUtils;
import org.springframework.util.Assert;
/**
@ -143,25 +143,33 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
/**
* Determine if the value for the {@link Parameter} in the supplied {@link ParameterContext}
* should be autowired from the test's {@link ApplicationContext}.
* <p>Returns {@code true} if the parameter is declared in a {@link Constructor}
* that is annotated with {@link Autowired @Autowired} or if the parameter is
* of type {@link ApplicationContext} (or a sub-type thereof) and otherwise delegates
* to {@link ParameterResolutionDelegate#isAutowirable}.
* <p><strong>WARNING</strong>: If the parameter is declared in a {@code Constructor}
* that is annotated with {@code @Autowired}, Spring will assume the responsibility
* for resolving all parameters in the constructor. Consequently, no other registered
* {@link ParameterResolver} will be able to resolve parameters.
* <p>A parameter is considered to be autowirable if one of the following
* conditions is {@code true}.
* <ol>
* <li>The {@linkplain ParameterContext#getDeclaringExecutable() declaring
* executable} is a {@link Constructor} and
* {@link TestConstructorUtils#isAutowirableConstructor(Constructor, Class)}
* returns {@code true}.</li>
* <li>The parameter is of type {@link ApplicationContext} or a sub-type thereof.</li>
* <li>{@link ParameterResolutionDelegate#isAutowirable} returns {@code true}.</li>
* </ol>
* <p><strong>WARNING</strong>: If a test class {@code Constructor} is annotated
* with {@code @Autowired} or automatically autowirable (see {@link TestConstructor}),
* Spring will assume the responsibility for resolving all parameters in the
* constructor. Consequently, no other registered {@link ParameterResolver}
* will be able to resolve parameters.
* @see #resolveParameter
* @see TestConstructorUtils#isAutowirableConstructor(Constructor, Class)
* @see ParameterResolutionDelegate#isAutowirable
*/
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
Parameter parameter = parameterContext.getParameter();
int index = parameterContext.getIndex();
Executable exec = parameter.getDeclaringExecutable();
return ((exec instanceof Constructor && AnnotatedElementUtils.hasAnnotation(exec, Autowired.class)) ||
Executable executable = parameter.getDeclaringExecutable();
Class<?> testClass = extensionContext.getRequiredTestClass();
return (TestConstructorUtils.isAutowirableConstructor(executable, testClass) ||
ApplicationContext.class.isAssignableFrom(parameter.getType()) ||
ParameterResolutionDelegate.isAutowirable(parameter, index));
ParameterResolutionDelegate.isAutowirable(parameter, parameterContext.getIndex()));
}
/**

View File

@ -0,0 +1,94 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.support;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.SpringProperties;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.test.context.TestConstructor;
/**
* Utility methods for working with {@link TestConstructor @TestConstructor}.
*
* <p>Primarily intended for use within the framework.
*
* @author Sam Brannen
* @since 5.2
* @see TestConstructor
*/
public abstract class TestConstructorUtils {
private TestConstructorUtils() {
}
/**
* Determine if the supplied executable for the given test class is an
* autowirable constructor.
*
* <p>This method delegates to {@link #isAutowirableConstructor(Constructor, Class)}
* if the executable is a constructor.
*
* @param executable an executable for the test class
* @param testClass the test class
* @return {@code true} if the executable is an autowirable constructor
* @see #isAutowirableConstructor(Constructor, Class)
*/
public static boolean isAutowirableConstructor(Executable executable, Class<?> testClass) {
return (executable instanceof Constructor &&
isAutowirableConstructor((Constructor<?>) executable, testClass));
}
/**
* Determine if the supplied constructor for the given test class is
* autowirable.
*
* <p>A constructor is considered to be autowirable if one of the following
* conditions is {@code true}.
*
* <ol>
* <li>The constructor is annotated with {@link Autowired @Autowired}.</li>
* <li>{@link TestConstructor @TestConstructor} is <em>present</em> or
* <em>meta-present</em> on the test class with
* {@link TestConstructor#autowire autowire} set to {@code true}.</li>
* <li>The default <em>test constructor autowire</em> mode is set to {@code true}
* (see {@link TestConstructor#TEST_CONSTRUCTOR_AUTOWIRE_PROPERTY_NAME}).</li>
* </ol>
*
* @param constructor a constructor for the test class
* @param testClass the test class
* @return {@code true} if the constructor is autowirable
* @see #isAutowirableConstructor(Executable, Class)
*/
public static boolean isAutowirableConstructor(Constructor<?> constructor, Class<?> testClass) {
// Is the constructor annotated with @Autowired?
if (AnnotatedElementUtils.hasAnnotation(constructor, Autowired.class)) {
return true;
}
// Is the test class annotated with @TestConstructor?
TestConstructor testConstructor = AnnotatedElementUtils.findMergedAnnotation(testClass, TestConstructor.class);
if (testConstructor != null) {
return testConstructor.autowire();
}
// Else use global default.
return SpringProperties.getFlag(TestConstructor.TEST_CONSTRUCTOR_AUTOWIRE_PROPERTY_NAME);
}
}

View File

@ -0,0 +1,86 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.junit.jupiter;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.TestConstructor;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.SpringJUnitJupiterTestSuite;
import org.springframework.test.context.junit.jupiter.comics.Dog;
import org.springframework.test.context.junit.jupiter.comics.Person;
import static org.junit.jupiter.api.Assertions.*;
/**
* Integration tests which demonstrate support for automatically
* {@link Autowired @Autowired} test class constructors in conjunction with the
* {@link TestConstructor @TestConstructor} annotation
*
* <p>To run these tests in an IDE that does not have built-in support for the JUnit
* Platform, simply run {@link SpringJUnitJupiterTestSuite} as a JUnit 4 test.
*
* @author Sam Brannen
* @since 5.2
* @see SpringExtension
* @see SpringJUnitJupiterAutowiredConstructorInjectionTests
* @see SpringJUnitJupiterConstructorInjectionTests
*/
@SpringJUnitConfig(TestConfig.class)
@TestPropertySource(properties = "enigma = 42")
@TestConstructor(autowire = true)
class TestConstructorAnnotationIntegrationTests {
final ApplicationContext applicationContext;
final Person dilbert;
final Dog dog;
final Integer enigma;
TestConstructorAnnotationIntegrationTests(ApplicationContext applicationContext, Person dilbert, Dog dog,
@Value("${enigma}") Integer enigma) {
this.applicationContext = applicationContext;
this.dilbert = dilbert;
this.dog = dog;
this.enigma = enigma;
}
@Test
void applicationContextInjected() {
assertNotNull(applicationContext, "ApplicationContext should have been injected by Spring");
assertEquals(this.dilbert, applicationContext.getBean("dilbert", Person.class));
}
@Test
void beansInjected() {
assertNotNull(this.dilbert, "Dilbert should have been @Autowired by Spring");
assertEquals("Dilbert", this.dilbert.getName(), "Person's name");
assertNotNull(this.dog, "Dogbert should have been @Autowired by Spring");
assertEquals("Dogbert", this.dog.getName(), "Dog's name");
}
@Test
void propertyPlaceholderInjected() {
assertNotNull(this.enigma, "Enigma should have been injected via @Value by Spring");
assertEquals(Integer.valueOf(42), this.enigma, "enigma");
}
}

View File

@ -0,0 +1,106 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.support;
import java.lang.reflect.Constructor;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.TestConstructor;
import static org.junit.Assert.*;
/**
* Unit tests for {@link TestConstructorUtils}.
*
* @author Sam Brannen
* @since 5.2
*/
public class TestConstructorUtilsTests {
@After
public void clearGlobalFlag() {
System.clearProperty(TestConstructor.TEST_CONSTRUCTOR_AUTOWIRE_PROPERTY_NAME);
}
@Test
public void notAutowirable() throws Exception {
assertNotAutowirable(NotAutowirableTestCase.class);
}
@Test
public void autowiredAnnotation() throws Exception {
assertAutowirable(AutowiredAnnotationTestCase.class);
}
@Test
public void testConstructorAnnotation() throws Exception {
assertAutowirable(TestConstructorAnnotationTestCase.class);
}
@Test
public void automaticallyAutowired() throws Exception {
setGlobalFlag();
assertAutowirable(AutomaticallyAutowiredTestCase.class);
}
@Test
public void automaticallyAutowiredButOverriddenLocally() throws Exception {
setGlobalFlag();
assertNotAutowirable(TestConstructorAnnotationOverridesGlobalFlagTestCase.class);
}
private void assertAutowirable(Class<?> testClass) throws NoSuchMethodException {
Constructor<?> constructor = testClass.getDeclaredConstructor();
assertTrue(TestConstructorUtils.isAutowirableConstructor(constructor, testClass));
}
private void assertNotAutowirable(Class<?> testClass) throws NoSuchMethodException {
Constructor<?> constructor = testClass.getDeclaredConstructor();
assertFalse(TestConstructorUtils.isAutowirableConstructor(constructor, testClass));
}
private void setGlobalFlag() {
System.setProperty(TestConstructor.TEST_CONSTRUCTOR_AUTOWIRE_PROPERTY_NAME, "true");
}
static class NotAutowirableTestCase {
}
@TestConstructor(autowire = false)
static class AutowiredAnnotationTestCase {
@Autowired
AutowiredAnnotationTestCase() {
}
}
@TestConstructor(autowire = true)
static class TestConstructorAnnotationTestCase {
}
static class AutomaticallyAutowiredTestCase {
}
@TestConstructor(autowire = false)
static class TestConstructorAnnotationOverridesGlobalFlagTestCase {
}
}