/
AbstractApplicationContextRunnerTests.java
340 lines (277 loc) · 11 KB
/
AbstractApplicationContextRunnerTests.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/*
* Copyright 2012-2021 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.boot.test.context.runner;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import com.google.gson.Gson;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.annotation.UserConfigurations;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.FilteredClassLoader;
import org.springframework.boot.test.context.assertj.ApplicationContextAssertProvider;
import org.springframework.boot.test.context.example.ExampleProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIOException;
/**
* Abstract tests for {@link AbstractApplicationContextRunner} implementations.
*
* @param <T> The runner type
* @param <C> the context type
* @param <A> the assertable context type
* @author Stephane Nicoll
* @author Phillip Webb
*/
abstract class AbstractApplicationContextRunnerTests<T extends AbstractApplicationContextRunner<T, C, A>, C extends ConfigurableApplicationContext, A extends ApplicationContextAssertProvider<C>> {
@Test
void runWithInitializerShouldInitialize() {
AtomicBoolean called = new AtomicBoolean();
get().withInitializer((context) -> called.set(true)).run((context) -> {
});
assertThat(called).isTrue();
}
@Test
void runWithSystemPropertiesShouldSetAndRemoveProperties() {
String key = "test." + UUID.randomUUID();
assertThat(System.getProperties().containsKey(key)).isFalse();
get().withSystemProperties(key + "=value")
.run((context) -> assertThat(System.getProperties()).containsEntry(key, "value"));
assertThat(System.getProperties().containsKey(key)).isFalse();
}
@Test
void runWithSystemPropertiesWhenContextFailsShouldRemoveProperties() {
String key = "test." + UUID.randomUUID();
assertThat(System.getProperties().containsKey(key)).isFalse();
get().withSystemProperties(key + "=value").withUserConfiguration(FailingConfig.class)
.run((context) -> assertThat(context).hasFailed());
assertThat(System.getProperties().containsKey(key)).isFalse();
}
@Test
void runWithSystemPropertiesShouldRestoreOriginalProperties() {
String key = "test." + UUID.randomUUID();
System.setProperty(key, "value");
try {
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
get().withSystemProperties(key + "=newValue")
.run((context) -> assertThat(System.getProperties()).containsEntry(key, "newValue"));
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
}
finally {
System.clearProperty(key);
}
}
@Test
void runWithSystemPropertiesWhenValueIsNullShouldRemoveProperty() {
String key = "test." + UUID.randomUUID();
System.setProperty(key, "value");
try {
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
get().withSystemProperties(key + "=")
.run((context) -> assertThat(System.getProperties()).doesNotContainKey(key));
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
}
finally {
System.clearProperty(key);
}
}
@Test
void runWithMultiplePropertyValuesShouldAllAllValues() {
get().withPropertyValues("test.foo=1").withPropertyValues("test.bar=2").run((context) -> {
Environment environment = context.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("1");
assertThat(environment.getProperty("test.bar")).isEqualTo("2");
});
}
@Test
void runWithPropertyValuesWhenHasExistingShouldReplaceValue() {
get().withPropertyValues("test.foo=1").withPropertyValues("test.foo=2").run((context) -> {
Environment environment = context.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("2");
});
}
@Test
void runWithConfigurationsShouldRegisterConfigurations() {
get().withUserConfiguration(FooConfig.class).run((context) -> assertThat(context).hasBean("foo"));
}
@Test
void runWithUserNamedBeanShouldRegisterBean() {
get().withBean("foo", String.class, () -> "foo").run((context) -> assertThat(context).hasBean("foo"));
}
@Test
void runWithUserBeanShouldRegisterBeanWithDefaultName() {
get().withBean(String.class, () -> "foo").run((context) -> assertThat(context).hasBean("string"));
}
@Test
void runWithMultipleConfigurationsShouldRegisterAllConfigurations() {
get().withUserConfiguration(FooConfig.class).withConfiguration(UserConfigurations.of(BarConfig.class))
.run((context) -> assertThat(context).hasBean("foo").hasBean("bar"));
}
@Test
void runWithFailedContextShouldReturnFailedAssertableContext() {
get().withUserConfiguration(FailingConfig.class).run((context) -> assertThat(context).hasFailed());
}
@Test
void runWithClassLoaderShouldSetClassLoaderOnContext() {
get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName()))
.run((context) -> assertThatExceptionOfType(ClassNotFoundException.class)
.isThrownBy(() -> ClassUtils.forName(Gson.class.getName(), context.getClassLoader())));
}
@Test
void runWithClassLoaderShouldSetClassLoaderOnConditionContext() {
get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName()))
.withUserConfiguration(ConditionalConfig.class)
.run((context) -> assertThat(context).hasSingleBean(ConditionalConfig.class));
}
@Test
void consecutiveRunWithFilteredClassLoaderShouldHaveBeanWithLazyProperties() {
get().withClassLoader(new FilteredClassLoader(Gson.class)).withUserConfiguration(LazyConfig.class)
.run((context) -> assertThat(context).hasSingleBean(ExampleBeanWithLazyProperties.class));
get().withClassLoader(new FilteredClassLoader(Gson.class)).withUserConfiguration(LazyConfig.class)
.run((context) -> assertThat(context).hasSingleBean(ExampleBeanWithLazyProperties.class));
}
@Test
void thrownRuleWorksWithCheckedException() {
get().run((context) -> assertThatIOException().isThrownBy(() -> throwCheckedException("Expected message"))
.withMessageContaining("Expected message"));
}
@Test
void runDisablesBeanOverridingByDefault() {
get().withUserConfiguration(FooConfig.class).withBean("foo", Integer.class, () -> 42).run((context) -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure()).isInstanceOf(BeanDefinitionStoreException.class)
.hasMessageContaining("Invalid bean definition with name 'foo'")
.hasMessageContaining("@Bean definition illegally overridden by existing bean definition");
});
}
@Test
void runDisablesCircularReferencesByDefault() {
get().withUserConfiguration(ExampleConsumerConfiguration.class, ExampleProducerConfiguration.class)
.run((context) -> {
assertThat(context).hasFailed();
assertThat(context).getFailure().hasRootCauseInstanceOf(BeanCurrentlyInCreationException.class);
});
}
@Test
void circularReferencesCanBeAllowed() {
get().withAllowCircularReferences(true)
.withUserConfiguration(ExampleConsumerConfiguration.class, ExampleProducerConfiguration.class)
.run((context) -> assertThat(context).hasNotFailed());
}
@Test
void runWithUserBeanShouldBeRegisteredInOrder() {
get().withAllowBeanDefinitionOverriding(true).withBean(String.class, () -> "one")
.withBean(String.class, () -> "two").withBean(String.class, () -> "three").run((context) -> {
assertThat(context).hasBean("string");
assertThat(context.getBean("string")).isEqualTo("three");
});
}
@Test
void runWithConfigurationsAndUserBeanShouldRegisterUserBeanLast() {
get().withAllowBeanDefinitionOverriding(true).withUserConfiguration(FooConfig.class)
.withBean("foo", String.class, () -> "overridden").run((context) -> {
assertThat(context).hasBean("foo");
assertThat(context.getBean("foo")).isEqualTo("overridden");
});
}
protected abstract T get();
private static void throwCheckedException(String message) throws IOException {
throw new IOException(message);
}
@Configuration(proxyBeanMethods = false)
static class FailingConfig {
@Bean
String foo() {
throw new IllegalStateException("Failed");
}
}
@Configuration(proxyBeanMethods = false)
static class FooConfig {
@Bean
String foo() {
return "foo";
}
}
@Configuration(proxyBeanMethods = false)
static class BarConfig {
@Bean
String bar() {
return "bar";
}
}
@Configuration(proxyBeanMethods = false)
@Conditional(FilteredClassLoaderCondition.class)
static class ConditionalConfig {
}
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ExampleProperties.class)
static class LazyConfig {
@Bean
ExampleBeanWithLazyProperties exampleBeanWithLazyProperties() {
return new ExampleBeanWithLazyProperties();
}
}
static class ExampleBeanWithLazyProperties {
@Autowired
@Lazy
ExampleProperties exampleProperties;
}
static class FilteredClassLoaderCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getClassLoader() instanceof FilteredClassLoader;
}
}
static class Example {
}
@FunctionalInterface
interface ExampleConfigurer {
void configure(Example example);
}
@Configuration(proxyBeanMethods = false)
static class ExampleProducerConfiguration {
@Bean
Example example(ObjectProvider<ExampleConfigurer> configurers) {
Example example = new Example();
configurers.orderedStream().forEach((configurer) -> configurer.configure(example));
return example;
}
}
@Configuration(proxyBeanMethods = false)
static class ExampleConsumerConfiguration {
@Autowired
Example example;
@Bean
ExampleConfigurer configurer() {
return (example) -> {
};
}
}
}