From 77eef47483b3fc6a5b08da457da1fa73606221aa Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Mon, 6 May 2019 19:34:50 +0200 Subject: [PATCH] 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 --- .../test/context/TestConstructor.java | 94 ++++++++++++++++ .../junit/jupiter/SpringExtension.java | 36 +++--- .../context/support/TestConstructorUtils.java | 94 ++++++++++++++++ ...ConstructorAnnotationIntegrationTests.java | 86 ++++++++++++++ .../support/TestConstructorUtilsTests.java | 106 ++++++++++++++++++ 5 files changed, 402 insertions(+), 14 deletions(-) create mode 100644 spring-test/src/main/java/org/springframework/test/context/TestConstructor.java create mode 100644 spring-test/src/main/java/org/springframework/test/context/support/TestConstructorUtils.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/junit/jupiter/TestConstructorAnnotationIntegrationTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/support/TestConstructorUtilsTests.java diff --git a/spring-test/src/main/java/org/springframework/test/context/TestConstructor.java b/spring-test/src/main/java/org/springframework/test/context/TestConstructor.java new file mode 100644 index 00000000000..8625e0db0c6 --- /dev/null +++ b/spring-test/src/main/java/org/springframework/test/context/TestConstructor.java @@ -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}. + * + *

If {@code @TestConstructor} is not present or meta-present + * on a test class, the default test constructor autowire 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. + * + *

This annotation may be used as a meta-annotation to create custom + * composed annotations. + * + *

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 — 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 test constructor autowire + * mode: {@value #TEST_CONSTRUCTOR_AUTOWIRE_PROPERTY_NAME}. + *

May alternatively be configured via the + * {@link org.springframework.core.SpringProperties SpringProperties} mechanism. + *

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 test constructor autowire mode for the + * current test class. + *

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(); + +} diff --git a/spring-test/src/main/java/org/springframework/test/context/junit/jupiter/SpringExtension.java b/spring-test/src/main/java/org/springframework/test/context/junit/jupiter/SpringExtension.java index ae7884ae319..6b2b4abeeb7 100644 --- a/spring-test/src/main/java/org/springframework/test/context/junit/jupiter/SpringExtension.java +++ b/spring-test/src/main/java/org/springframework/test/context/junit/jupiter/SpringExtension.java @@ -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}. - *

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}. - *

WARNING: 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. + *

A parameter is considered to be autowirable if one of the following + * conditions is {@code true}. + *

    + *
  1. The {@linkplain ParameterContext#getDeclaringExecutable() declaring + * executable} is a {@link Constructor} and + * {@link TestConstructorUtils#isAutowirableConstructor(Constructor, Class)} + * returns {@code true}.
  2. + *
  3. The parameter is of type {@link ApplicationContext} or a sub-type thereof.
  4. + *
  5. {@link ParameterResolutionDelegate#isAutowirable} returns {@code true}.
  6. + *
+ *

WARNING: 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())); } /** diff --git a/spring-test/src/main/java/org/springframework/test/context/support/TestConstructorUtils.java b/spring-test/src/main/java/org/springframework/test/context/support/TestConstructorUtils.java new file mode 100644 index 00000000000..d946033676e --- /dev/null +++ b/spring-test/src/main/java/org/springframework/test/context/support/TestConstructorUtils.java @@ -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}. + * + *

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. + * + *

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. + * + *

A constructor is considered to be autowirable if one of the following + * conditions is {@code true}. + * + *

    + *
  1. The constructor is annotated with {@link Autowired @Autowired}.
  2. + *
  3. {@link TestConstructor @TestConstructor} is present or + * meta-present on the test class with + * {@link TestConstructor#autowire autowire} set to {@code true}.
  4. + *
  5. The default test constructor autowire mode is set to {@code true} + * (see {@link TestConstructor#TEST_CONSTRUCTOR_AUTOWIRE_PROPERTY_NAME}).
  6. + *
+ * + * @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); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/TestConstructorAnnotationIntegrationTests.java b/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/TestConstructorAnnotationIntegrationTests.java new file mode 100644 index 00000000000..bc048ed7670 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/TestConstructorAnnotationIntegrationTests.java @@ -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 + * + *

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"); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/support/TestConstructorUtilsTests.java b/spring-test/src/test/java/org/springframework/test/context/support/TestConstructorUtilsTests.java new file mode 100644 index 00000000000..87707d7c62e --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/support/TestConstructorUtilsTests.java @@ -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 { + } + +}