|
| 1 | +/* |
| 2 | + * Copyright 2012-present the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.boot.test.autoconfigure; |
| 18 | + |
| 19 | +import java.lang.annotation.Annotation; |
| 20 | + |
| 21 | +import org.springframework.boot.test.context.SpringBootTestContextBootstrapper; |
| 22 | +import org.springframework.core.ResolvableType; |
| 23 | +import org.springframework.core.annotation.MergedAnnotation; |
| 24 | +import org.springframework.core.annotation.MergedAnnotations; |
| 25 | +import org.springframework.core.annotation.MergedAnnotations.SearchStrategy; |
| 26 | +import org.springframework.test.context.TestContextAnnotationUtils; |
| 27 | +import org.springframework.test.context.TestContextBootstrapper; |
| 28 | +import org.springframework.util.Assert; |
| 29 | + |
| 30 | +/** |
| 31 | + * Base class for test slice {@link TestContextBootstrapper test context bootstrappers}. |
| 32 | + * |
| 33 | + * @param <T> the test slice annotation |
| 34 | + * @author Yanming Zhou |
| 35 | + * @since 4.0.0 |
| 36 | + */ |
| 37 | +public abstract class TestSliceTestContextBootstrapper<T extends Annotation> extends SpringBootTestContextBootstrapper { |
| 38 | + |
| 39 | + private final Class<T> annotationType; |
| 40 | + |
| 41 | + @SuppressWarnings("unchecked") |
| 42 | + protected TestSliceTestContextBootstrapper() { |
| 43 | + this.annotationType = (Class<T>) ResolvableType.forClass(getClass()) |
| 44 | + .as(TestSliceTestContextBootstrapper.class) |
| 45 | + .getGeneric(0) |
| 46 | + .resolve(); |
| 47 | + Assert.notNull(this.annotationType, "'%s' doesn't contain type parameter of '%s'" |
| 48 | + .formatted(getClass().getName(), TestSliceTestContextBootstrapper.class.getName())); |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + protected String[] getProperties(Class<?> testClass) { |
| 53 | + MergedAnnotation<T> annotation = MergedAnnotations.search(SearchStrategy.TYPE_HIERARCHY) |
| 54 | + .withEnclosingClasses(TestContextAnnotationUtils::searchEnclosingClass) |
| 55 | + .from(testClass) |
| 56 | + .get(this.annotationType); |
| 57 | + return annotation.isPresent() ? annotation.getStringArray("properties") : null; |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments