Relocate projects to spring-boot-project

Move projects to better reflect the way that Spring Boot is released.

The following projects are under `spring-boot-project`:

  - `spring-boot`
  - `spring-boot-autoconfigure`
  - `spring-boot-tools`
  - `spring-boot-starters`
  - `spring-boot-actuator`
  - `spring-boot-actuator-autoconfigure`
  - `spring-boot-test`
  - `spring-boot-test-autoconfigure`
  - `spring-boot-devtools`
  - `spring-boot-cli`
  - `spring-boot-docs`

See gh-9316
This commit is contained in:
Phillip Webb
2017-09-19 14:29:46 -07:00
parent 0419d42b7c
commit 0ba4830b4f
4023 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,120 @@
/*
* Copyright 2012-2017 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
*
* http://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;
import org.junit.Test;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.embedded.tomcat.TomcatReactiveWebServerFactory;
import org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext;
import org.springframework.boot.web.reactive.server.ReactiveWebServerFactory;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Base class for {@link SpringBootTest} tests configured to start an embedded reactive
* container.
*
* @author Stephane Nicoll
*/
public abstract class AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests {
@LocalServerPort
private int port = 0;
@Value("${value}")
private int value = 0;
@Autowired
private ReactiveWebApplicationContext context;
@Autowired
private WebTestClient webClient;
@Autowired
private TestRestTemplate restTemplate;
public ReactiveWebApplicationContext getContext() {
return this.context;
}
@Test
public void runAndTestHttpEndpoint() {
assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0);
WebTestClient.bindToServer().baseUrl("http://localhost:" + this.port).build()
.get().uri("/").exchange().expectBody(String.class)
.isEqualTo("Hello World");
}
@Test
public void injectWebTestClient() {
this.webClient.get().uri("/").exchange().expectBody(String.class)
.isEqualTo("Hello World");
}
@Test
public void injectTestRestTemplate() {
String body = this.restTemplate.getForObject("/", String.class);
assertThat(body).isEqualTo("Hello World");
}
@Test
public void annotationAttributesOverridePropertiesFile() throws Exception {
assertThat(this.value).isEqualTo(123);
}
protected static class AbstractConfig {
@Value("${server.port:8080}")
private int port = 8080;
@Bean
public HttpHandler httpHandler(ApplicationContext applicationContext) {
return WebHttpHandlerBuilder.applicationContext(applicationContext).build();
}
@Bean
public ReactiveWebServerFactory webServerFactory() {
TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory();
factory.setPort(this.port);
return factory;
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholder() {
return new PropertySourcesPlaceholderConfigurer();
}
@RequestMapping("/")
public Mono<String> home() {
return Mono.just("Hello World");
}
}
}

View File

@@ -0,0 +1,124 @@
/*
* Copyright 2012-2017 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
*
* http://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;
import javax.servlet.ServletContext;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.DispatcherServlet;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Base class for {@link SpringBootTest} tests configured to start an embedded web server.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public abstract class AbstractSpringBootTestWebServerWebEnvironmentTests {
@LocalServerPort
private int port = 0;
@Value("${value}")
private int value = 0;
@Autowired
private WebApplicationContext context;
@Autowired
private ServletContext servletContext;
@Autowired
private TestRestTemplate restTemplate;
public WebApplicationContext getContext() {
return this.context;
}
public TestRestTemplate getRestTemplate() {
return this.restTemplate;
}
@Test
public void runAndTestHttpEndpoint() {
assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0);
String body = new RestTemplate()
.getForObject("http://localhost:" + this.port + "/", String.class);
assertThat(body).isEqualTo("Hello World");
}
@Test
public void injectTestRestTemplate() {
String body = this.restTemplate.getForObject("/", String.class);
assertThat(body).isEqualTo("Hello World");
}
@Test
public void annotationAttributesOverridePropertiesFile() throws Exception {
assertThat(this.value).isEqualTo(123);
}
@Test
public void validateWebApplicationContextIsSet() {
assertThat(this.context).isSameAs(
WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
}
protected static class AbstractConfig {
@Value("${server.port:8080}")
private int port = 8080;
@Bean
public DispatcherServlet dispatcherServlet() {
return new DispatcherServlet();
}
@Bean
public ServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.setPort(this.port);
return factory;
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholder() {
return new PropertySourcesPlaceholderConfigurer();
}
@RequestMapping("/")
public String home() {
return "Hello World";
}
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ConfigFileApplicationContextInitializer}.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@ContextConfiguration(classes = ConfigFileApplicationContextInitializerTests.Config.class, initializers = ConfigFileApplicationContextInitializer.class)
public class ConfigFileApplicationContextInitializerTests {
@Autowired
private Environment environment;
@Test
public void initializerPopulatesEnvironment() {
assertThat(this.environment.getProperty("foo")).isEqualTo("bucket");
}
@Configuration
public static class Config {
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.ImportsContextCustomizerFactoryIntegrationTests.ImportedBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for {@link ImportsContextCustomizerFactory} and
* {@link ImportsContextCustomizer}.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@Import(ImportedBean.class)
public class ImportsContextCustomizerFactoryIntegrationTests {
@Autowired
private ApplicationContext context;
@Autowired
private ImportedBean bean;
@Test
public void beanWasImported() throws Exception {
assertThat(this.bean).isNotNull();
}
@Test(expected = NoSuchBeanDefinitionException.class)
public void testItselfIsNotABean() throws Exception {
this.context.getBean(getClass());
}
@Component
static class ImportedBean {
}
}

View File

@@ -0,0 +1,175 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextCustomizer;
import org.springframework.test.context.MergedContextConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link ImportsContextCustomizerFactory} and {@link ImportsContextCustomizer}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class ImportsContextCustomizerFactoryTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private ImportsContextCustomizerFactory factory = new ImportsContextCustomizerFactory();
@Test
public void getContextCustomizerWhenHasNoImportAnnotationShouldReturnNull() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(TestWithNoImport.class, null);
assertThat(customizer).isNull();
}
@Test
public void getContextCustomizerWhenHasImportAnnotationShouldReturnCustomizer() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(TestWithImport.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void getContextCustomizerWhenHasMetaImportAnnotationShouldReturnCustomizer() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(TestWithMetaImport.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void contextCustomizerEqualsAndHashCode() throws Exception {
ContextCustomizer customizer1 = this.factory
.createContextCustomizer(TestWithImport.class, null);
ContextCustomizer customizer2 = this.factory
.createContextCustomizer(TestWithImport.class, null);
ContextCustomizer customizer3 = this.factory
.createContextCustomizer(TestWithImportAndMetaImport.class, null);
ContextCustomizer customizer4 = this.factory
.createContextCustomizer(TestWithSameImportAndMetaImport.class, null);
assertThat(customizer1.hashCode()).isEqualTo(customizer1.hashCode());
assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode());
assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2)
.isNotEqualTo(customizer3);
assertThat(customizer3).isEqualTo(customizer4);
}
@Test
public void getContextCustomizerWhenClassHasBeanMethodsShouldThrowException()
throws Exception {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Test classes cannot include @Bean methods");
this.factory.createContextCustomizer(TestWithImportAndBeanMethod.class, null);
}
@Test
public void contextCustomizerImportsBeans() throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(TestWithImport.class, null);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
customizer.customizeContext(context, mock(MergedContextConfiguration.class));
context.refresh();
assertThat(context.getBean(ImportedBean.class)).isNotNull();
}
@Test
public void selfAnnotatingAnnotationDoesNotCauseStackOverflow() {
assertThat(this.factory.createContextCustomizer(
TestWithImportAndSelfAnnotatingAnnotation.class, null)).isNotNull();
}
static class TestWithNoImport {
}
@Import(ImportedBean.class)
static class TestWithImport {
}
@MetaImport
static class TestWithMetaImport {
}
@MetaImport
@Import(AnotherImportedBean.class)
static class TestWithImportAndMetaImport {
}
@MetaImport
@Import(AnotherImportedBean.class)
static class TestWithSameImportAndMetaImport {
}
@Import(ImportedBean.class)
static class TestWithImportAndBeanMethod {
@Bean
public String bean() {
return "bean";
}
}
@SelfAnnotating
@Import(ImportedBean.class)
static class TestWithImportAndSelfAnnotatingAnnotation {
}
@Retention(RetentionPolicy.RUNTIME)
@Import(ImportedBean.class)
@interface MetaImport {
}
@Component
static class ImportedBean {
}
@Component
static class AnotherImportedBean {
}
@Retention(RetentionPolicy.RUNTIME)
@SelfAnnotating
static @interface SelfAnnotating {
}
}

View File

@@ -0,0 +1,175 @@
/*
* Copyright 2012-2017 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
*
* http://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;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collections;
import java.util.Set;
import kotlin.Metadata;
import org.junit.Test;
import org.spockframework.runtime.model.SpecMetadata;
import spock.lang.Issue;
import spock.lang.Stepwise;
import org.springframework.boot.context.annotation.DeterminableImports;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ImportsContextCustomizer}.
*
* @author Andy Wilkinson
*/
public class ImportsContextCustomizerTests {
@Test
public void importSelectorsCouldUseAnyAnnotations() throws Exception {
assertThat(new ImportsContextCustomizer(FirstImportSelectorAnnotatedClass.class))
.isNotEqualTo(new ImportsContextCustomizer(
SecondImportSelectorAnnotatedClass.class));
}
@Test
public void determinableImportSelector() throws Exception {
assertThat(new ImportsContextCustomizer(
FirstDeterminableImportSelectorAnnotatedClass.class))
.isEqualTo(new ImportsContextCustomizer(
SecondDeterminableImportSelectorAnnotatedClass.class));
}
@Test
public void customizersForTestClassesWithDifferentKotlinMetadataAreEqual() {
assertThat(new ImportsContextCustomizer(FirstKotlinAnnotatedTestClass.class))
.isEqualTo(new ImportsContextCustomizer(
SecondKotlinAnnotatedTestClass.class));
}
@Test
public void customizersForTestClassesWithDifferentSpockFrameworkAnnotationsAreEqual() {
assertThat(
new ImportsContextCustomizer(FirstSpockFrameworkAnnotatedTestClass.class))
.isEqualTo(new ImportsContextCustomizer(
SecondSpockFrameworkAnnotatedTestClass.class));
}
@Test
public void customizersForTestClassesWithDifferentSpockLangAnnotationsAreEqual() {
assertThat(new ImportsContextCustomizer(FirstSpockLangAnnotatedTestClass.class))
.isEqualTo(new ImportsContextCustomizer(
SecondSpockLangAnnotatedTestClass.class));
}
@Import(TestImportSelector.class)
@Indicator1
static class FirstImportSelectorAnnotatedClass {
}
@Import(TestImportSelector.class)
@Indicator2
static class SecondImportSelectorAnnotatedClass {
}
@Import(TestDeterminableImportSelector.class)
@Indicator1
static class FirstDeterminableImportSelectorAnnotatedClass {
}
@Import(TestDeterminableImportSelector.class)
@Indicator2
static class SecondDeterminableImportSelectorAnnotatedClass {
}
@Metadata(d2 = "foo")
static class FirstKotlinAnnotatedTestClass {
}
@Metadata(d2 = "bar")
static class SecondKotlinAnnotatedTestClass {
}
@SpecMetadata(filename = "foo", line = 10)
static class FirstSpockFrameworkAnnotatedTestClass {
}
@SpecMetadata(filename = "bar", line = 10)
static class SecondSpockFrameworkAnnotatedTestClass {
}
@Stepwise
static class FirstSpockLangAnnotatedTestClass {
}
@Issue("1234")
static class SecondSpockLangAnnotatedTestClass {
}
@Retention(RetentionPolicy.RUNTIME)
@interface Indicator1 {
}
@Retention(RetentionPolicy.RUNTIME)
@interface Indicator2 {
}
static class TestImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata arg0) {
return new String[] {};
}
}
static class TestDeterminableImportSelector
implements ImportSelector, DeterminableImports {
@Override
public String[] selectImports(AnnotationMetadata arg0) {
return new String[] { TestConfig.class.getName() };
}
@Override
public Set<Object> determineImports(AnnotationMetadata metadata) {
return Collections.<Object>singleton(TestConfig.class.getName());
}
}
@Configuration
static class TestConfig {
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.test.context.example.ExampleConfig;
import org.springframework.boot.test.context.example.scan.Example;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootConfigurationFinder}.
*
* @author Phillip Webb
*/
public class SpringBootConfigurationFinderTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private SpringBootConfigurationFinder finder = new SpringBootConfigurationFinder();
@Test
public void findFromClassWhenSourceIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Source must not be null");
this.finder.findFromClass((Class<?>) null);
}
@Test
public void findFromPackageWhenSourceIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Source must not be null");
this.finder.findFromPackage((String) null);
}
@Test
public void findFromPackageWhenNoConfigurationFoundShouldReturnNull() {
Class<?> config = this.finder.findFromPackage("org.springframework.boot");
assertThat(config).isNull();
}
@Test
public void findFromClassWhenConfigurationIsFoundShouldReturnConfiguration() {
Class<?> config = this.finder.findFromClass(Example.class);
assertThat(config).isEqualTo(ExampleConfig.class);
}
@Test
public void findFromPackageWhenConfigurationIsFoundShouldReturnConfiguration() {
Class<?> config = this.finder
.findFromPackage("org.springframework.boot.test.context.example.scan");
assertThat(config).isEqualTo(ExampleConfig.class);
}
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import javax.servlet.ServletContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Tests for {@link WebAppConfiguration} integration.
*
* @author Stephane Nicoll
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@ContextConfiguration(loader = SpringBootContextLoader.class)
@WebAppConfiguration
public class SpringBootContextLoaderMockMvcTests {
@Autowired
private WebApplicationContext context;
@Autowired
private ServletContext servletContext;
private MockMvc mvc;
@Before
public void setUp() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
@Test
public void testMockHttpEndpoint() throws Exception {
this.mvc.perform(get("/")).andExpect(status().isOk())
.andExpect(content().string("Hello World"));
}
@Test
public void validateWebApplicationContextIsSet() {
assertThat(this.context).isSameAs(
WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
}
@Configuration
@EnableWebMvc
@RestController
protected static class Config {
@RequestMapping("/")
public String home() {
return "Hello World";
}
}
}

View File

@@ -0,0 +1,169 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestContextManager;
import org.springframework.test.context.support.TestPropertySourceUtils;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootContextLoader}
*
* @author Stephane Nicoll
*/
public class SpringBootContextLoaderTests {
@Test
public void environmentPropertiesSimple() throws Exception {
Map<String, Object> config = getEnvironmentProperties(SimpleConfig.class);
assertKey(config, "key", "myValue");
assertKey(config, "anotherKey", "anotherValue");
}
@Test
public void environmentPropertiesSimpleNonAlias() throws Exception {
Map<String, Object> config = getEnvironmentProperties(SimpleConfigNonAlias.class);
assertKey(config, "key", "myValue");
assertKey(config, "anotherKey", "anotherValue");
}
@Test
public void environmentPropertiesOverrideDefaults() throws Exception {
Map<String, Object> config = getEnvironmentProperties(OverrideConfig.class);
assertKey(config, "server.port", "2345");
}
@Test
public void environmentPropertiesAppend() throws Exception {
Map<String, Object> config = getEnvironmentProperties(AppendConfig.class);
assertKey(config, "key", "myValue");
assertKey(config, "otherKey", "otherValue");
}
@Test
public void environmentPropertiesSeparatorInValue() throws Exception {
Map<String, Object> config = getEnvironmentProperties(SameSeparatorInValue.class);
assertKey(config, "key", "my=Value");
assertKey(config, "anotherKey", "another:Value");
}
@Test
public void environmentPropertiesAnotherSeparatorInValue() throws Exception {
Map<String, Object> config = getEnvironmentProperties(
AnotherSeparatorInValue.class);
assertKey(config, "key", "my:Value");
assertKey(config, "anotherKey", "another=Value");
}
@Test
@Ignore
public void environmentPropertiesNewLineInValue() throws Exception {
// gh-4384
Map<String, Object> config = getEnvironmentProperties(NewLineInValue.class);
assertKey(config, "key", "myValue");
assertKey(config, "variables", "foo=FOO\n bar=BAR");
}
private Map<String, Object> getEnvironmentProperties(Class<?> testClass)
throws Exception {
TestContext context = new ExposedTestContextManager(testClass)
.getExposedTestContext();
MergedContextConfiguration config = (MergedContextConfiguration) ReflectionTestUtils
.getField(context, "mergedContextConfiguration");
return TestPropertySourceUtils
.convertInlinedPropertiesToMap(config.getPropertySourceProperties());
}
private void assertKey(Map<String, Object> actual, String key, Object value) {
assertThat(actual.containsKey(key)).as("Key '" + key + "' not found").isTrue();
assertThat(actual.get(key)).isEqualTo(value);
}
@SpringBootTest({ "key=myValue", "anotherKey:anotherValue" })
@ContextConfiguration(classes = Config.class)
static class SimpleConfig {
}
@SpringBootTest(properties = { "key=myValue", "anotherKey:anotherValue" })
@ContextConfiguration(classes = Config.class)
static class SimpleConfigNonAlias {
}
@SpringBootTest("server.port=2345")
@ContextConfiguration(classes = Config.class)
static class OverrideConfig {
}
@SpringBootTest({ "key=myValue", "otherKey=otherValue" })
@ContextConfiguration(classes = Config.class)
static class AppendConfig {
}
@SpringBootTest({ "key=my=Value", "anotherKey:another:Value" })
@ContextConfiguration(classes = Config.class)
static class SameSeparatorInValue {
}
@SpringBootTest({ "key=my:Value", "anotherKey:another=Value" })
@ContextConfiguration(classes = Config.class)
static class AnotherSeparatorInValue {
}
@SpringBootTest({ "key=myValue", "variables=foo=FOO\n bar=BAR" })
@ContextConfiguration(classes = Config.class)
static class NewLineInValue {
}
@Configuration
static class Config {
}
/**
* {@link TestContextManager} which exposes the {@link TestContext}.
*/
private static class ExposedTestContextManager extends TestContextManager {
ExposedTestContextManager(Class<?> testClass) {
super(testClass);
}
public final TestContext getExposedTestContext() {
return super.getTestContext();
}
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTest} with active profiles. See gh-1469.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest("spring.config.name=enableother")
@ActiveProfiles("override")
public class SpringBootTestActiveProfileTests {
@Autowired
private ApplicationContext context;
@Test
public void profiles() throws Exception {
assertThat(this.context.getEnvironment().getActiveProfiles())
.containsExactly("override");
}
@Configuration
protected static class Config {
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2012-2017 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTestContextHierarchyTests.ChildConfiguration;
import org.springframework.boot.test.context.SpringBootTestContextHierarchyTests.ParentConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Tests for {@link SpringBootTest} and {@link ContextHierarchy}.
*
* @author Andy Wilkinson
*/
@SpringBootTest
@ContextHierarchy({ @ContextConfiguration(classes = ParentConfiguration.class),
@ContextConfiguration(classes = ChildConfiguration.class) })
@RunWith(SpringRunner.class)
public class SpringBootTestContextHierarchyTests {
@Test
public void contextLoads() {
}
@Configuration
static class ParentConfiguration {
@Bean
MyBean myBean() {
return new MyBean();
}
}
@Configuration
static class ChildConfiguration {
ChildConfiguration(MyBean myBean) {
}
}
static class MyBean {
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@SpringBootTest} with a custom config name
*
* @author Andy Wilkinson
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.config.name=custom-config-name")
public class SpringBootTestCustomConfigNameTests {
@Value("${test.foo}")
private String foo;
@Test
public void propertyIsLoadedFromConfigFileWithCustomName() {
assertThat(this.foo).isEqualTo("bar");
}
@Configuration
static class TestConfiguration {
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link SpringBootTest} with a custom inline server.port in a non-embedded web
* environment.
*
* @author Stephane Nicoll
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "server.port=12345")
public class SpringBootTestCustomPortTests {
@Autowired
private Environment environment;
@Test
public void validatePortIsNotOverwritten() {
String port = this.environment.getProperty("server.port");
assertThat(port).isEqualTo("12345");
}
@Configuration
protected static class Config {
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTest} (detectDefaultConfigurationClasses).
*
* @author Dave Syer
*/
@RunWith(SpringRunner.class)
@DirtiesContext
public class SpringBootTestDefaultConfigurationTests {
@Autowired
private Config config;
@Test
public void nestedConfigClasses() {
assertThat(this.config).isNotNull();
}
@Configuration
protected static class Config {
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTest} (detectDefaultConfigurationClasses).
*
* @author Dave Syer
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest
@ContextConfiguration(locations = "classpath:test.groovy")
public class SpringBootTestGroovyConfigurationTests {
@Autowired
private String foo;
@Test
public void groovyConfigLoaded() {
assertThat(this.foo).isNotNull();
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTest} finding groovy config.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@DirtiesContext
public class SpringBootTestGroovyConventionConfigurationTests {
@Autowired
private String foo;
@Test
public void groovyConfigLoaded() {
assertThat(this.foo).isEqualTo("World");
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for disabling JMX by default
*
* @author Dave Syer
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest
public class SpringBootTestJmxTests {
@Value("${spring.jmx.enabled}")
private boolean jmx;
@Test
public void disabledByDefault() {
assertThat(this.jmx).isFalse();
}
@Configuration
protected static class Config {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTestMixedConfigurationTests.Config;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTest}.
*
* @author Dave Syer
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest
@ContextConfiguration(classes = Config.class, locations = "classpath:test.groovy")
public class SpringBootTestMixedConfigurationTests {
@Autowired
private String foo;
@Autowired
private Config config;
@Test
public void mixedConfigClasses() {
assertThat(this.foo).isNotNull();
assertThat(this.config).isNotNull();
}
@Configuration
protected static class Config {
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2012-2017 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
*
* http://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;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.config.EnableWebFlux;
/**
* Tests for {@link SpringBootTest} in a reactive environment configured with
* {@link WebEnvironment#DEFINED_PORT}.
*
* @author Stephane Nicoll
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = {
"spring.main.web-application-type=reactive", "server.port=0", "value=123" })
public class SpringBootTestReactiveWebEnvironmentDefinedPortTests
extends AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests {
@Configuration
@EnableWebFlux
@RestController
protected static class Config extends AbstractConfig {
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2012-2017 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
*
* http://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;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.config.EnableWebFlux;
/**
* Tests for {@link SpringBootTest} in a reactive environment configured with
* {@link WebEnvironment#RANDOM_PORT}.
*
* @author Stephane Nicoll
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = {
"spring.main.webApplicationType=reactive", "value=123" })
public class SpringBootTestReactiveWebEnvironmentRandomPortTests
extends AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests {
@Configuration
@EnableWebFlux
@RestController
protected static class Config extends AbstractConfig {
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright 2012-2017 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.config.EnableWebFlux;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTest} in a reactive environment configured with a
* user-defined {@link RestTemplate} that is named {@code testRestTemplate}.
*
* @author Madhura Bhave
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = {
"spring.main.web-application-type=reactive", "value=123" })
public class SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTests
extends AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests {
@Test
public void restTemplateIsUserDefined() throws Exception {
assertThat(getContext().getBean("testRestTemplate"))
.isInstanceOf(RestTemplate.class);
}
@Configuration
@EnableWebFlux
@RestController
protected static class Config extends AbstractConfig {
@Bean
public RestTemplate testRestTemplate() {
return new RestTemplate();
}
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright 2012-2017 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTest} configured with a user-defined {@link RestTemplate}
* that is named {@code testRestTemplate}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" })
public class SpringBootTestUserDefinedTestRestTemplateTests
extends AbstractSpringBootTestWebServerWebEnvironmentTests {
@Test
public void restTemplateIsUserDefined() throws Exception {
assertThat(getContext().getBean("testRestTemplate"))
.isInstanceOf(RestTemplate.class);
}
// gh-7711
@Configuration
@EnableWebMvc
@RestController
protected static class Config extends AbstractConfig {
@Bean
public RestTemplate testRestTemplate() {
return new RestTemplate();
}
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright 2012-2017 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.AbstractSpringBootTestWebServerWebEnvironmentTests.AbstractConfig;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.context.SpringBootTestWebEnvironmentContextHierarchyTests.ChildConfiguration;
import org.springframework.boot.test.context.SpringBootTestWebEnvironmentContextHierarchyTests.ParentConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTest} configured with {@link WebEnvironment#DEFINED_PORT}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = {
"server.port=0", "value=123" })
@ContextHierarchy({ @ContextConfiguration(classes = ParentConfiguration.class),
@ContextConfiguration(classes = ChildConfiguration.class) })
public class SpringBootTestWebEnvironmentContextHierarchyTests {
@Autowired
private ApplicationContext context;
@Test
public void testShouldOnlyStartSingleServer() throws Exception {
ApplicationContext parent = this.context.getParent();
assertThat(this.context).isInstanceOf(WebApplicationContext.class);
assertThat(parent).isNotInstanceOf(WebApplicationContext.class);
}
@Configuration
protected static class ParentConfiguration extends AbstractConfig {
}
@Configuration
@EnableWebMvc
@RestController
protected static class ChildConfiguration extends AbstractConfig {
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2012-2017 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
*
* http://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;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* Tests for {@link SpringBootTest} configured with {@link WebEnvironment#DEFINED_PORT}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = {
"server.port=0", "value=123" })
public class SpringBootTestWebEnvironmentDefinedPortTests
extends AbstractSpringBootTestWebServerWebEnvironmentTests {
@Configuration
@EnableWebMvc
@RestController
protected static class Config extends AbstractConfig {
}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import javax.servlet.ServletContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTest} configured with {@link WebEnvironment#MOCK}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
@RunWith(SpringRunner.class)
@SpringBootTest("value=123")
@DirtiesContext
public class SpringBootTestWebEnvironmentMockTests {
@Value("${value}")
private int value = 0;
@Autowired
private WebApplicationContext context;
@Autowired
private ServletContext servletContext;
@Test
public void annotationAttributesOverridePropertiesFile() throws Exception {
assertThat(this.value).isEqualTo(123);
}
@Test
public void validateWebApplicationContextIsSet() {
WebApplicationContext fromServletContext = WebApplicationContextUtils
.getWebApplicationContext(this.servletContext);
assertThat(fromServletContext).isSameAs(this.context);
}
@Test
public void setsRequestContextHolder() throws Exception {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
assertThat(attributes).isNotNull();
}
@Test
public void resourcePath() throws Exception {
assertThat(ReflectionTestUtils.getField(this.servletContext, "resourceBasePath"))
.isEqualTo("src/main/webapp");
}
@Configuration
@EnableWebMvc
protected static class Config {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholder() {
return new PropertySourcesPlaceholderConfigurer();
}
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import javax.servlet.ServletContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTest} configured with {@link WebEnvironment#MOCK}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@DirtiesContext
@WebAppConfiguration("src/mymain/mywebapp")
public class SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests {
@Autowired
private ServletContext servletContext;
@Test
public void resourcePath() throws Exception {
assertThat(ReflectionTestUtils.getField(this.servletContext, "resourceBasePath"))
.isEqualTo("src/mymain/mywebapp");
}
@Configuration
@EnableWebMvc
protected static class Config {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholder() {
return new PropertySourcesPlaceholderConfigurer();
}
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright 2012-2017 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.AbstractSpringBootTestWebServerWebEnvironmentTests.AbstractConfig;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link SpringBootTest} with a custom inline server.port in an embedded web
* environment.
*
* @author Stephane Nicoll
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = {
"server.port=12345" })
public class SpringBootTestWebEnvironmentRandomPortCustomPortTests {
@Autowired
private Environment environment;
@Test
public void validatePortIsNotOverwritten() {
String port = this.environment.getProperty("server.port");
assertThat(port).isEqualTo("0");
}
@Configuration
@EnableWebMvc
protected static class Config extends AbstractConfig {
}
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright 2012-2017 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTest} configured with {@link WebEnvironment#RANDOM_PORT}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" })
public class SpringBootTestWebEnvironmentRandomPortTests
extends AbstractSpringBootTestWebServerWebEnvironmentTests {
@Test
public void testRestTemplateShouldUseBuilder() throws Exception {
assertThat(getRestTemplate().getRestTemplate().getMessageConverters())
.hasAtLeastOneElementOfType(MyConverter.class);
}
@Configuration
@EnableWebMvc
@RestController
protected static class Config extends AbstractConfig {
@Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder()
.additionalMessageConverters(new MyConverter());
}
}
private static class MyConverter extends StringHttpMessageConverter {
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTest} configured with specific classes.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(classes = SpringBootTestWithClassesIntegrationTests.Config.class)
public class SpringBootTestWithClassesIntegrationTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Autowired
private ApplicationContext context;
@Test
public void injectsOnlyConfig() throws Exception {
assertThat(this.context.getBean(Config.class)).isNotNull();
this.thrown.expect(NoSuchBeanDefinitionException.class);
this.context.getBean(AdditionalConfig.class);
}
@Configuration
static class Config {
}
@Configuration
static class AdditionalConfig {
}
}

View File

@@ -0,0 +1,68 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTest} configured with {@link ContextConfiguration}.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest
@ContextConfiguration(classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class)
public class SpringBootTestWithContextConfigurationIntegrationTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Autowired
private ApplicationContext context;
@Test
public void injectsOnlyConfig() throws Exception {
assertThat(this.context.getBean(Config.class)).isNotNull();
this.thrown.expect(NoSuchBeanDefinitionException.class);
this.context.getBean(AdditionalConfig.class);
}
@Configuration
static class Config {
}
@Configuration
static class AdditionalConfig {
}
}

View File

@@ -0,0 +1,113 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for using {@link SpringBootTest} with {@link TestPropertySource}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.NONE, properties = {
"boot-test-inlined=foo", "b=boot-test-inlined", "c=boot-test-inlined" })
@TestPropertySource(properties = { "property-source-inlined=bar",
"a=property-source-inlined",
"c=property-source-inlined" }, locations = "classpath:/test-property-source-annotation.properties")
public class SpringBootTestWithTestPropertySourceTests {
@Autowired
private Config config;
@Test
public void propertyFromSpringBootTestProperties() {
assertThat(this.config.bootTestInlined).isEqualTo("foo");
}
@Test
public void propertyFromTestPropertySourceProperties() {
assertThat(this.config.propertySourceInlined).isEqualTo("bar");
}
@Test
public void propertyFromTestPropertySourceLocations() {
assertThat(this.config.propertySourceLocation).isEqualTo("baz");
}
@Test
public void propertyFromPropertySourcePropertiesOverridesPropertyFromPropertySourceLocations() {
assertThat(this.config.propertySourceInlinedOverridesPropertySourceLocation)
.isEqualTo("property-source-inlined");
}
@Test
public void propertyFromBootTestPropertiesOverridesPropertyFromPropertySourceLocations() {
assertThat(this.config.bootTestInlinedOverridesPropertySourceLocation)
.isEqualTo("boot-test-inlined");
}
@Test
public void propertyFromPropertySourcePropertiesOverridesPropertyFromBootTestProperties() {
assertThat(this.config.propertySourceInlinedOverridesBootTestInlined)
.isEqualTo("property-source-inlined");
}
@Configuration
static class Config {
@Value("${boot-test-inlined}")
private String bootTestInlined;
@Value("${property-source-inlined}")
private String propertySourceInlined;
@Value("${property-source-location}")
private String propertySourceLocation;
@Value("${a}")
private String propertySourceInlinedOverridesPropertySourceLocation;
@Value("${b}")
private String bootTestInlinedOverridesPropertySourceLocation;
@Value("${c}")
private String propertySourceInlinedOverridesBootTestInlined;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholder() {
return new PropertySourcesPlaceholderConfigurer();
}
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2012-2016 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
*
* http://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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTest} finding XML config.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest
public class SpringBootTestXmlConventionConfigurationTests {
@Autowired
private String foo;
@Test
public void xmlConfigLoaded() {
assertThat(this.foo).isEqualTo("World");
}
}

View File

@@ -0,0 +1,245 @@
/*
* Copyright 2012-2017 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
*
* http://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.assertj;
import java.util.function.Supplier;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.StaticApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link ApplicationContextAssertProvider} and
* {@link AssertProviderApplicationContextInvocationHandler}.
*
* @author Phillip Webb
*/
public class ApplicationContextAssertProviderTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Mock
private ConfigurableApplicationContext mockContext;
private RuntimeException startupFailure;
private Supplier<ApplicationContext> mockContextSupplier;
private Supplier<ApplicationContext> startupFailureSupplier;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.startupFailure = new RuntimeException();
this.mockContextSupplier = () -> this.mockContext;
this.startupFailureSupplier = () -> {
throw this.startupFailure;
};
}
@Test
public void getWhenTypeIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Type must not be null");
ApplicationContextAssertProvider.get(null, ApplicationContext.class,
this.mockContextSupplier);
}
@Test
public void getWhenTypeIsClassShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Type must not be null");
ApplicationContextAssertProvider.get(null, ApplicationContext.class,
this.mockContextSupplier);
}
@Test
public void getWhenContextTypeIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Type must be an interface");
ApplicationContextAssertProvider.get(
TestAssertProviderApplicationContextClass.class, ApplicationContext.class,
this.mockContextSupplier);
}
@Test
public void getWhenContextTypeIsClassShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ContextType must not be null");
ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class,
null, this.mockContextSupplier);
}
@Test
public void getWhenSupplierIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ContextType must be an interface");
ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class,
StaticApplicationContext.class, this.mockContextSupplier);
}
@Test
public void getWhenContextStartsShouldReturnProxyThatCallsRealMethods()
throws Exception {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
assertThat((Object) context).isNotNull();
context.getBean("foo");
verify(this.mockContext).getBean("foo");
}
@Test
public void getWhenContextFailsShouldReturnProxyThatThrowsExceptions()
throws Exception {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
assertThat((Object) context).isNotNull();
expectStartupFailure();
context.getBean("foo");
}
@Test
public void getSourceContextWhenContextStartsShouldReturnSourceContext()
throws Exception {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
assertThat(context.getSourceApplicationContext()).isSameAs(this.mockContext);
}
@Test
public void getSourceContextWhenContextFailsShouldThrowException() throws Exception {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
expectStartupFailure();
context.getSourceApplicationContext();
}
@Test
public void getSourceContextOfTypeWhenContextStartsShouldReturnSourceContext()
throws Exception {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
assertThat(context.getSourceApplicationContext(ApplicationContext.class))
.isSameAs(this.mockContext);
}
@Test
public void getSourceContextOfTypeWhenContextFailsToStartShouldThrowException()
throws Exception {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
expectStartupFailure();
context.getSourceApplicationContext(ApplicationContext.class);
}
@Test
public void getStartupFailureWhenContextStartsShouldReturnNull() throws Exception {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
assertThat(context.getStartupFailure()).isNull();
}
@Test
public void getStartupFailureWhenContextFailsToStartShouldReturnException()
throws Exception {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
assertThat(context.getStartupFailure()).isEqualTo(this.startupFailure);
}
@Test
public void assertThatWhenContextStartsShouldReturnAssertions() throws Exception {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
ApplicationContextAssert<ApplicationContext> contextAssert = assertThat(context);
assertThat(contextAssert.getApplicationContext()).isSameAs(context);
assertThat(contextAssert.getStartupFailure()).isNull();
}
@Test
public void assertThatWhenContextFailsShouldReturnAssertions() throws Exception {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
ApplicationContextAssert<ApplicationContext> contextAssert = assertThat(context);
assertThat(contextAssert.getApplicationContext()).isSameAs(context);
assertThat(contextAssert.getStartupFailure()).isSameAs(this.startupFailure);
}
@Test
public void toStringWhenContextStartsShouldReturnSimpleString() throws Exception {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
assertThat(context.toString())
.startsWith(
"Started application org.springframework.context.ConfigurableApplicationContext$MockitoMock")
.endsWith("[id=<null>,applicationName=<null>,beanDefinitionCount=0]");
}
@Test
public void toStringWhenContextFailsToStartShouldReturnSimpleString()
throws Exception {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
assertThat(context.toString()).isEqualTo("Unstarted application context "
+ "org.springframework.context.ApplicationContext"
+ "[startupFailure=java.lang.RuntimeException]");
}
@Test
public void closeShouldCloseContext() throws Exception {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
context.close();
verify(this.mockContext).close();
}
private void expectStartupFailure() {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("failed to start");
this.thrown.expectCause(equalTo(this.startupFailure));
}
private ApplicationContextAssertProvider<ApplicationContext> get(
Supplier<ApplicationContext> contextSupplier) {
return ApplicationContextAssertProvider.get(
TestAssertProviderApplicationContext.class, ApplicationContext.class,
contextSupplier);
}
private interface TestAssertProviderApplicationContext
extends ApplicationContextAssertProvider<ApplicationContext> {
}
private abstract static class TestAssertProviderApplicationContextClass
implements TestAssertProviderApplicationContext {
}
}

View File

@@ -0,0 +1,330 @@
/*
* Copyright 2012-2017 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
*
* http://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.assertj;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.StaticApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ApplicationContextAssert}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class ApplicationContextAssertTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private StaticApplicationContext context = new StaticApplicationContext();
private RuntimeException failure = new RuntimeException();
@Test
public void createWhenApplicationContextIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ApplicationContext must not be null");
new ApplicationContextAssert<>(null, null);
}
@Test
public void createWhenHasApplicationContextShouldSetActual() {
assertThat(getAssert(this.context).getSourceApplicationContext())
.isSameAs(this.context);
}
@Test
public void createWhenHasExceptionShouldSetFailure() {
assertThat(getAssert(this.failure)).getFailure().isSameAs(this.failure);
}
@Test
public void hasBeanWhenHasBeanShouldPass() {
this.context.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).hasBean("foo");
}
@Test
public void hasBeanWhenHasNoBeanShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("no such bean");
assertThat(getAssert(this.context)).hasBean("foo");
}
@Test
public void hasBeanWhenNotStartedShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("failed to start");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).hasBean("foo");
}
@Test
public void hasSingleBeanWhenHasSingleBeanShouldPass() {
this.context.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).hasSingleBean(Foo.class);
}
@Test
public void hasSingleBeanWhenHasNoBeansShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to have a single bean of type");
assertThat(getAssert(this.context)).hasSingleBean(Foo.class);
}
@Test
public void hasSingleBeanWhenHasMultipleShouldFail() {
this.context.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("but found:");
assertThat(getAssert(this.context)).hasSingleBean(Foo.class);
}
@Test
public void hasSingleBeanWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to have a single bean of type");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).hasSingleBean(Foo.class);
}
@Test
public void doesNotHaveBeanOfTypeWhenHasNoBeanOfTypeShouldPass() {
assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class);
}
@Test
public void doesNotHaveBeanOfTypeWhenHasBeanOfTypeShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("but found");
this.context.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class);
}
@Test
public void doesNotHaveBeanOfTypeWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("not to have any beans of type");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class);
}
@Test
public void doesNotHaveBeanOfNameWhenHasNoBeanOfTypeShouldPass() {
assertThat(getAssert(this.context)).doesNotHaveBean("foo");
}
@Test
public void doesNotHaveBeanOfNameWhenHasBeanOfTypeShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("but found");
this.context.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).doesNotHaveBean("foo");
}
@Test
public void doesNotHaveBeanOfNameWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("not to have any beans of name");
this.thrown.expectMessage("failed to start");
assertThat(getAssert(this.failure)).doesNotHaveBean("foo");
}
@Test
public void getBeanNamesWhenHasNamesShouldReturnNamesAssert() {
this.context.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThat(getAssert(this.context)).getBeanNames(Foo.class).containsOnly("foo",
"bar");
}
@Test
public void getBeanNamesWhenHasNoNamesShouldReturnEmptyAssert() {
assertThat(getAssert(this.context)).getBeanNames(Foo.class).isEmpty();
}
@Test
public void getBeanNamesWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("not to have any beans of name");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).doesNotHaveBean("foo");
}
@Test
public void getBeanOfTypeWhenHasBeanShouldReturnBeanAssert() {
this.context.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).getBean(Foo.class).isNotNull();
}
@Test
public void getBeanOfTypeWhenHasNoBeanShouldReturnNullAssert() {
assertThat(getAssert(this.context)).getBean(Foo.class).isNull();
}
@Test
public void getBeanOfTypeWhenHasMultipleBeansShouldFail() {
this.context.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("but found");
assertThat(getAssert(this.context)).getBean(Foo.class);
}
@Test
public void getBeanOfTypeWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to contain bean of type");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).getBean(Foo.class);
}
@Test
public void getBeanOfNameWhenHasBeanShouldReturnBeanAssert() {
this.context.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).getBean("foo").isNotNull();
}
@Test
public void getBeanOfNameWhenHasNoBeanOfNameShouldReturnNullAssert() {
assertThat(getAssert(this.context)).getBean("foo").isNull();
}
@Test
public void getBeanOfNameWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to contain a bean of name");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).getBean("foo");
}
@Test
public void getBeanOfNameAndTypeWhenHasBeanShouldReturnBeanAssert() {
this.context.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).getBean("foo", Foo.class).isNotNull();
}
@Test
public void getBeanOfNameAndTypeWhenHasNoBeanOfNameShouldReturnNullAssert() {
assertThat(getAssert(this.context)).getBean("foo", Foo.class).isNull();
}
@Test
public void getBeanOfNameAndTypeWhenHasNoBeanOfNameButDifferentTypeShouldFail() {
this.context.registerSingleton("foo", Foo.class);
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("of type");
assertThat(getAssert(this.context)).getBean("foo", String.class);
}
@Test
public void getBeanOfNameAndTypeWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to contain a bean of name");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).getBean("foo", Foo.class);
}
@Test
public void getBeansWhenHasBeansShouldReturnMapAssert() {
this.context.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2)
.containsKeys("foo", "bar");
}
@Test
public void getBeansWhenHasNoBeansShouldReturnEmptyMapAssert() {
assertThat(getAssert(this.context)).getBeans(Foo.class).isEmpty();
}
@Test
public void getBeansWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to get beans of type");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).getBeans(Foo.class);
}
@Test
public void getFailureWhenFailedShouldReturnFailure() {
assertThat(getAssert(this.failure)).getFailure().isSameAs(this.failure);
}
@Test
public void getFailureWhenDidNotFailShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("context started");
assertThat(getAssert(this.context)).getFailure();
}
@Test
public void hasFailedWhenFailedShouldPass() {
assertThat(getAssert(this.failure)).hasFailed();
}
@Test
public void hasFailedWhenNotFailedShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to have failed");
assertThat(getAssert(this.context)).hasFailed();
}
@Test
public void hasNotFailedWhenFailedShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to have not failed");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).hasNotFailed();
}
@Test
public void hasNotFailedWhenNotFailedShouldPass() {
assertThat(getAssert(this.context)).hasNotFailed();
}
private AssertableApplicationContext getAssert(
ConfigurableApplicationContext applicationContext) {
return AssertableApplicationContext.get(() -> applicationContext);
}
private AssertableApplicationContext getAssert(RuntimeException failure) {
return AssertableApplicationContext.get(() -> {
throw failure;
});
}
private static class Foo {
}
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2012-2017 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
*
* http://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.assertj;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link AssertableApplicationContext}.
*
* @author Phillip Webb
* @see ApplicationContextAssertProviderTests
*/
public class AssertableApplicationContextTests {
@Test
public void getShouldReturnProxy() {
AssertableApplicationContext context = AssertableApplicationContext
.get(() -> mock(ConfigurableApplicationContext.class));
assertThat(context).isInstanceOf(ConfigurableApplicationContext.class);
}
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2012-2017 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
*
* http://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.assertj;
import org.junit.Test;
import org.springframework.boot.web.reactive.context.ConfigurableReactiveWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link AssertableReactiveWebApplicationContext}.
*
* @author Phillip Webb
* @see ApplicationContextAssertProviderTests
*/
public class AssertableReactiveWebApplicationContextTests {
@Test
public void getShouldReturnProxy() {
AssertableReactiveWebApplicationContext context = AssertableReactiveWebApplicationContext
.get(() -> mock(ConfigurableReactiveWebApplicationContext.class));
assertThat(context).isInstanceOf(ConfigurableReactiveWebApplicationContext.class);
}
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2012-2017 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
*
* http://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.assertj;
import org.junit.Test;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link AssertableWebApplicationContext}.
*
* @author Phillip Webb
* @see ApplicationContextAssertProviderTests
*/
public class AssertableWebApplicationContextTests {
@Test
public void getShouldReturnProxy() {
AssertableWebApplicationContext context = AssertableWebApplicationContext
.get(() -> mock(ConfigurableWebApplicationContext.class));
assertThat(context).isInstanceOf(ConfigurableWebApplicationContext.class);
}
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2012-2016 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
*
* http://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.bootstrap;
import org.springframework.boot.SpringBootConfiguration;
/**
* Example configuration used in
* {@link SpringBootTestContextBootstrapperIntegrationTests}.
*
* @author Phillip Webb
*/
@SpringBootConfiguration
public class SpringBootTestContextBootstrapperExampleConfig {
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright 2012-2016 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
*
* http://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.bootstrap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTestContextBootstrapper;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.BootstrapWith;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for {@link SpringBootTestContextBootstrapper} (in its own package so
* we can test detection).
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@BootstrapWith(SpringBootTestContextBootstrapper.class)
public class SpringBootTestContextBootstrapperIntegrationTests {
@Autowired
private ApplicationContext context;
@Autowired
private SpringBootTestContextBootstrapperExampleConfig config;
boolean defaultTestExecutionListenersPostProcessorCalled = false;
@Test
public void findConfigAutomatically() throws Exception {
assertThat(this.config).isNotNull();
}
@Test
public void contextWasCreatedViaSpringApplication() throws Exception {
assertThat(this.context.getId()).startsWith("application:");
}
@Test
public void testConfigurationWasApplied() throws Exception {
assertThat(this.context.getBean(ExampleBean.class)).isNotNull();
}
@Test
public void defaultTestExecutionListenersPostProcessorShouldBeCalled()
throws Exception {
assertThat(this.defaultTestExecutionListenersPostProcessorCalled).isTrue();
}
@TestConfiguration
static class TestConfig {
@Bean
public ExampleBean exampleBean() {
return new ExampleBean();
}
}
static class ExampleBean {
}
}

View File

@@ -0,0 +1,83 @@
/*
* Copyright 2012-2016 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
*
* http://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.bootstrap;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.context.SpringBootTestContextBootstrapper;
import org.springframework.test.context.BootstrapContext;
import org.springframework.test.context.CacheAwareContextLoaderDelegate;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link SpringBootTestContextBootstrapper}.
*
* @author Andy Wilkinson
*/
public class SpringBootTestContextBootstrapperTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void springBootTestWithANonMockWebEnvironmentAndWebAppConfigurationFailsFast() {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("@WebAppConfiguration should only be used with "
+ "@SpringBootTest when @SpringBootTest is configured with a mock web "
+ "environment. Please remove @WebAppConfiguration or reconfigure "
+ "@SpringBootTest.");
buildTestContext(SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class);
}
@Test
public void springBootTestWithAMockWebEnvironmentCanBeUsedWithWebAppConfiguration() {
buildTestContext(SpringBootTestMockWebEnvironmentAndWebAppConfiguration.class);
}
@SuppressWarnings("rawtypes")
private void buildTestContext(Class<?> testClass) {
SpringBootTestContextBootstrapper bootstrapper = new SpringBootTestContextBootstrapper();
BootstrapContext bootstrapContext = mock(BootstrapContext.class);
bootstrapper.setBootstrapContext(bootstrapContext);
given((Class) bootstrapContext.getTestClass()).willReturn(testClass);
CacheAwareContextLoaderDelegate contextLoaderDelegate = mock(
CacheAwareContextLoaderDelegate.class);
given(bootstrapContext.getCacheAwareContextLoaderDelegate())
.willReturn(contextLoaderDelegate);
bootstrapper.buildTestContext();
}
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@WebAppConfiguration
private static class SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration {
}
@SpringBootTest
@WebAppConfiguration
private static class SpringBootTestMockWebEnvironmentAndWebAppConfiguration {
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright 2012-2016 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
*
* http://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.bootstrap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTestContextBootstrapper;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.BootstrapWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootTestContextBootstrapper} + {@code @ContextConfiguration} (in
* its own package so we can test detection).
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@ContextConfiguration
public class SpringBootTestContextBootstrapperWithContextConfigurationTests {
@Autowired
private ApplicationContext context;
@Autowired
private SpringBootTestContextBootstrapperExampleConfig config;
@Test
public void findConfigAutomatically() throws Exception {
assertThat(this.config).isNotNull();
}
@Test
public void contextWasCreatedViaSpringApplication() throws Exception {
assertThat(this.context.getId()).startsWith("application:");
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright 2012-2017 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
*
* http://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.bootstrap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTestContextBootstrapper;
import org.springframework.boot.test.context.bootstrap.SpringBootTestContextBootstrapperWithInitializersTests.CustomInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.BootstrapWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for {@link SpringBootTestContextBootstrapper} with
* {@link ApplicationContextInitializer}.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@ContextConfiguration(initializers = CustomInitializer.class)
public class SpringBootTestContextBootstrapperWithInitializersTests {
@Autowired
private ApplicationContext context;
@Test
public void foundConfiguration() throws Exception {
Object bean = this.context
.getBean(SpringBootTestContextBootstrapperExampleConfig.class);
assertThat(bean).isNotNull();
}
// gh-8483
public static class CustomInitializer
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
}
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright 2012-2016 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
*
* http://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.bootstrap;
import java.util.Set;
import org.springframework.boot.test.context.DefaultTestExecutionListenersPostProcessor;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestExecutionListener;
import org.springframework.test.context.support.AbstractTestExecutionListener;
/**
* Test {@link DefaultTestExecutionListenersPostProcessor}.
*
* @author Phillip Webb
*/
public class TestDefaultTestExecutionListenersPostProcessor
implements DefaultTestExecutionListenersPostProcessor {
@Override
public Set<Class<? extends TestExecutionListener>> postProcessDefaultTestExecutionListeners(
Set<Class<? extends TestExecutionListener>> listeners) {
listeners.add(ExampleTestExecutionListener.class);
return listeners;
}
static class ExampleTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
Object testInstance = testContext.getTestInstance();
if (testInstance instanceof SpringBootTestContextBootstrapperIntegrationTests) {
SpringBootTestContextBootstrapperIntegrationTests test = (SpringBootTestContextBootstrapperIntegrationTests) testInstance;
test.defaultTestExecutionListenersPostProcessorCalled = true;
}
}
}
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2012-2016 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
*
* http://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.example;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootConfigurationFinderTests;
/**
* Example config used in {@link SpringBootConfigurationFinderTests}.
*
* @author Phillip Webb
*/
@SpringBootConfiguration
public class ExampleConfig {
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2012-2016 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
*
* http://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.example.scan;
import org.springframework.boot.test.context.SpringBootConfigurationFinderTests;
/**
* Example class used in {@link SpringBootConfigurationFinderTests}.
*
* @author Phillip Webb
*/
public class Example {
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright 2012-2016 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
*
* http://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.example.scan.sub;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootConfigurationFinderTests;
/**
* Example config used in {@link SpringBootConfigurationFinderTests}. Should not be found
* since scanner should only search upwards.
*
* @author Phillip Webb
*/
@SpringBootConfiguration
public class SubExampleConfig {
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2012-2017 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
*
* http://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.filter;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
public abstract class AbstractJupiterTestWithConfigAndExtendWith {
@Configuration
static class Config {
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2012-2016 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
*
* http://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.filter;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Abstract test with nest {@code @Configuration} and {@code @RunWith} used by
* {@link TestTypeExcludeFilter}.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
public abstract class AbstractTestWithConfigAndRunWith {
@Configuration
static class Config {
}
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2012-2017 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
*
* http://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.filter;
import org.junit.jupiter.api.RepeatedTest;
public class JupiterRepeatedTestExample {
@RepeatedTest(5)
public void repeatedTest() {
}
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2012-2017 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
*
* http://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.filter;
import org.junit.jupiter.api.Test;
public class JupiterTestExample {
@Test
public void repeatedTest() {
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2012-2017 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
*
* http://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.filter;
import java.util.Arrays;
import java.util.Collection;
import org.junit.jupiter.api.DynamicNode;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
public class JupiterTestFactoryExample {
@TestFactory
public Collection<DynamicNode> testFactory() {
return Arrays.asList(DynamicTest.dynamicTest("Some dynamic test", () -> {
// Test
}));
}
}

View File

@@ -0,0 +1,24 @@
/*
* Copyright 2012-2016 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
*
* http://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.filter;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SampleConfig {
}

View File

@@ -0,0 +1,26 @@
/*
* Copyright 2012-2016 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
*
* http://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.filter;
import org.springframework.boot.test.context.TestComponent;
import org.springframework.context.annotation.Configuration;
@Configuration
@TestComponent
public class SampleTestConfig {
}

View File

@@ -0,0 +1,110 @@
/*
* Copyright 2012-2017 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
*
* http://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.filter;
import java.io.IOException;
import org.junit.Test;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link TestTypeExcludeFilter}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class TestTypeExcludeFilterTests {
private TestTypeExcludeFilter filter = new TestTypeExcludeFilter();
private MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
@Test
public void matchesJUnit4TestClass() throws Exception {
assertThat(this.filter.match(getMetadataReader(TestTypeExcludeFilterTests.class),
this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesJUnitJupiterTestClass() throws Exception {
assertThat(this.filter.match(getMetadataReader(JupiterTestExample.class),
this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesJUnitJupiterRepeatedTestClass() throws Exception {
assertThat(this.filter.match(getMetadataReader(JupiterRepeatedTestExample.class),
this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesJUnitJupiterTestFactoryClass() throws Exception {
assertThat(this.filter.match(getMetadataReader(JupiterTestFactoryExample.class),
this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesNestedConfiguration() throws Exception {
assertThat(this.filter.match(getMetadataReader(NestedConfig.class),
this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith()
throws Exception {
assertThat(this.filter.match(
getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class),
this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasExtendWith()
throws Exception {
assertThat(this.filter.match(
getMetadataReader(
AbstractJupiterTestWithConfigAndExtendWith.Config.class),
this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesTestConfiguration() throws Exception {
assertThat(this.filter.match(getMetadataReader(SampleTestConfig.class),
this.metadataReaderFactory)).isTrue();
}
@Test
public void doesNotMatchRegularConfiguration() throws Exception {
assertThat(this.filter.match(getMetadataReader(SampleConfig.class),
this.metadataReaderFactory)).isFalse();
}
private MetadataReader getMetadataReader(Class<?> source) throws IOException {
return this.metadataReaderFactory.getMetadataReader(source.getName());
}
@Configuration
static class NestedConfig {
}
}

View File

@@ -0,0 +1,210 @@
/*
* Copyright 2012-2017 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
*
* http://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 com.google.gson.Gson;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.context.annotation.UserConfigurations;
import org.springframework.boot.test.context.HidePackagesClassLoader;
import org.springframework.boot.test.context.assertj.ApplicationContextAssertProvider;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
/**
* 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
*/
public abstract class AbstractApplicationContextRunnerTests<T extends AbstractApplicationContextRunner<T, C, A>, C extends ConfigurableApplicationContext, A extends ApplicationContextAssertProvider<C>> {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void runWithSystemPropertiesShouldSetAndRemoveProperties() {
String key = "test." + UUID.randomUUID().toString();
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
public void runWithSystemPropertiesWhenContextFailsShouldRemoveProperties()
throws Exception {
String key = "test." + UUID.randomUUID().toString();
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
public void runWithSystemPropertiesShouldRestoreOriginalProperties()
throws Exception {
String key = "test." + UUID.randomUUID().toString();
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
public void runWithSystemPropertiesWhenValueIsNullShouldRemoveProperty()
throws Exception {
String key = "test." + UUID.randomUUID().toString();
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
public void runWithMultiplePropertyValuesShouldAllAllValues() throws Exception {
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
public void runWithPropertyValuesWhenHasExistingShouldReplaceValue()
throws Exception {
get().withPropertyValues("test.foo=1").withPropertyValues("test.foo=2")
.run((context) -> {
Environment environment = context.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("2");
});
}
@Test
public void runWithConfigurationsShouldRegisterConfigurations() throws Exception {
get().withUserConfiguration(FooConfig.class)
.run((context) -> assertThat(context).hasBean("foo"));
}
@Test
public void runWithMultipleConfigurationsShouldRegisterAllConfigurations()
throws Exception {
get().withUserConfiguration(FooConfig.class)
.withConfiguration(UserConfigurations.of(BarConfig.class))
.run((context) -> assertThat(context).hasBean("foo").hasBean("bar"));
}
@Test
public void runWithFailedContextShouldReturnFailedAssertableContext()
throws Exception {
get().withUserConfiguration(FailingConfig.class)
.run((context) -> assertThat(context).hasFailed());
}
@Test
public void runWithClassLoaderShouldSetClassLoader() throws Exception {
get().withClassLoader(
new HidePackagesClassLoader(Gson.class.getPackage().getName()))
.run((context) -> {
try {
ClassUtils.forName(Gson.class.getName(),
context.getClassLoader());
fail("Should have thrown a ClassNotFoundException");
}
catch (ClassNotFoundException e) {
// expected
}
});
}
@Test
public void thrownRuleWorksWithCheckedException() {
get().run((context) -> {
this.thrown.expect(IOException.class);
this.thrown.expectMessage("Expected message");
throwCheckedException("Expected message");
});
}
protected abstract T get();
private static void throwCheckedException(String message) throws IOException {
throw new IOException(message);
}
@Configuration
static class FailingConfig {
@Bean
public String foo() {
throw new IllegalStateException("Failed");
}
}
@Configuration
static class FooConfig {
@Bean
public String foo() {
return "foo";
}
}
@Configuration
static class BarConfig {
@Bean
public String bar() {
return "bar";
}
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2012-2017 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
*
* http://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 org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
/**
* Tests for {@link ApplicationContextRunner}.
*
* @author Stephane Nicoll
* @author Phillip Webb
*/
public class ApplicationContextRunnerTests extends
AbstractApplicationContextRunnerTests<ApplicationContextRunner, ConfigurableApplicationContext, AssertableApplicationContext> {
@Override
protected ApplicationContextRunner get() {
return new ApplicationContextRunner();
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2012-2017 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
*
* http://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 org.springframework.boot.test.context.assertj.AssertableReactiveWebApplicationContext;
import org.springframework.boot.web.reactive.context.ConfigurableReactiveWebApplicationContext;
/**
* Tests for {@link ReactiveWebApplicationContextRunner}.
*
* @author Stephane Nicoll
* @author Phillip Webb
*/
public class ReactiveWebApplicationContextRunnerTests extends
AbstractApplicationContextRunnerTests<ReactiveWebApplicationContextRunner, ConfigurableReactiveWebApplicationContext, AssertableReactiveWebApplicationContext> {
@Override
protected ReactiveWebApplicationContextRunner get() {
return new ReactiveWebApplicationContextRunner();
}
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2012-2017 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
*
* http://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 org.junit.Test;
import org.springframework.boot.test.context.assertj.AssertableWebApplicationContext;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link WebApplicationContextRunner}.
*
* @author Stephane Nicoll
* @author Phillip Webb
*/
public class WebApplicationContextRunnerTests extends
AbstractApplicationContextRunnerTests<WebApplicationContextRunner, ConfigurableWebApplicationContext, AssertableWebApplicationContext> {
@Test
public void contextShouldHaveMockServletContext() throws Exception {
get().run((context) -> assertThat(context.getServletContext())
.isInstanceOf(MockServletContext.class));
}
@Override
protected WebApplicationContextRunner get() {
return new WebApplicationContextRunner();
}
}

View File

@@ -0,0 +1,212 @@
/*
* Copyright 2012-2017 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
*
* http://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.json;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link AbstractJsonMarshalTester}.
*
* @author Phillip Webb
*/
public abstract class AbstractJsonMarshalTesterTests {
private static final String JSON = "{\"name\":\"Spring\",\"age\":123}";
private static final String MAP_JSON = "{\"a\":" + JSON + "}";
private static final String ARRAY_JSON = "[" + JSON + "]";
private static final ExampleObject OBJECT = createExampleObject("Spring", 123);
private static final ResolvableType TYPE = ResolvableType
.forClass(ExampleObject.class);
@Rule
public ExpectedException thrown = ExpectedException.none();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void writeShouldReturnJsonContent() throws Exception {
JsonContent<Object> content = createTester(TYPE).write(OBJECT);
assertThat(content).isEqualToJson(JSON);
}
@Test
public void writeListShouldReturnJsonContent() throws Exception {
ResolvableType type = ResolvableTypes.get("listOfExampleObject");
List<ExampleObject> value = Collections.singletonList(OBJECT);
JsonContent<Object> content = createTester(type).write(value);
assertThat(content).isEqualToJson(ARRAY_JSON);
}
@Test
public void writeArrayShouldReturnJsonContent() throws Exception {
ResolvableType type = ResolvableTypes.get("arrayOfExampleObject");
ExampleObject[] value = new ExampleObject[] { OBJECT };
JsonContent<Object> content = createTester(type).write(value);
assertThat(content).isEqualToJson(ARRAY_JSON);
}
@Test
public void writeMapShouldReturnJsonContent() throws Exception {
ResolvableType type = ResolvableTypes.get("mapOfExampleObject");
Map<String, Object> value = new LinkedHashMap<>();
value.put("a", OBJECT);
JsonContent<Object> content = createTester(type).write(value);
assertThat(content).isEqualToJson(MAP_JSON);
}
@Test
public void createWhenResourceLoadClassIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ResourceLoadClass must not be null");
createTester(null, ResolvableType.forClass(ExampleObject.class));
}
@Test
public void createWhenTypeIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Type must not be null");
createTester(getClass(), null);
}
@Test
public void parseBytesShouldReturnObject() throws Exception {
AbstractJsonMarshalTester<Object> tester = createTester(TYPE);
assertThat(tester.parse(JSON.getBytes())).isEqualTo(OBJECT);
}
@Test
public void parseStringShouldReturnObject() throws Exception {
AbstractJsonMarshalTester<Object> tester = createTester(TYPE);
assertThat(tester.parse(JSON)).isEqualTo(OBJECT);
}
@Test
public void readResourcePathShouldReturnObject() throws Exception {
AbstractJsonMarshalTester<Object> tester = createTester(TYPE);
assertThat(tester.read("example.json")).isEqualTo(OBJECT);
}
@Test
public void readFileShouldReturnObject() throws Exception {
File file = this.temp.newFile("example.json");
FileCopyUtils.copy(JSON.getBytes(), file);
AbstractJsonMarshalTester<Object> tester = createTester(TYPE);
assertThat(tester.read(file)).isEqualTo(OBJECT);
}
@Test
public void readInputStreamShouldReturnObject() throws Exception {
InputStream stream = new ByteArrayInputStream(JSON.getBytes());
AbstractJsonMarshalTester<Object> tester = createTester(TYPE);
assertThat(tester.read(stream)).isEqualTo(OBJECT);
}
@Test
public void readResourceShouldReturnObject() throws Exception {
Resource resource = new ByteArrayResource(JSON.getBytes());
AbstractJsonMarshalTester<Object> tester = createTester(TYPE);
assertThat(tester.read(resource)).isEqualTo(OBJECT);
}
@Test
public void readReaderShouldReturnObject() throws Exception {
Reader reader = new StringReader(JSON);
AbstractJsonMarshalTester<Object> tester = createTester(TYPE);
assertThat(tester.read(reader)).isEqualTo(OBJECT);
}
@Test
public void parseListShouldReturnContent() throws Exception {
ResolvableType type = ResolvableTypes.get("listOfExampleObject");
AbstractJsonMarshalTester<Object> tester = createTester(type);
assertThat(tester.parse(ARRAY_JSON)).asList().containsOnly(OBJECT);
}
@Test
public void parseArrayShouldReturnContent() throws Exception {
ResolvableType type = ResolvableTypes.get("arrayOfExampleObject");
AbstractJsonMarshalTester<Object> tester = createTester(type);
assertThat(tester.parse(ARRAY_JSON)).asArray().containsOnly(OBJECT);
}
@Test
public void parseMapShouldReturnContent() throws Exception {
ResolvableType type = ResolvableTypes.get("mapOfExampleObject");
AbstractJsonMarshalTester<Object> tester = createTester(type);
assertThat(tester.parse(MAP_JSON)).asMap().containsEntry("a", OBJECT);
}
protected static final ExampleObject createExampleObject(String name, int age) {
ExampleObject exampleObject = new ExampleObject();
exampleObject.setName(name);
exampleObject.setAge(age);
return exampleObject;
}
protected final AbstractJsonMarshalTester<Object> createTester(ResolvableType type) {
return createTester(AbstractJsonMarshalTesterTests.class, type);
}
protected abstract AbstractJsonMarshalTester<Object> createTester(
Class<?> resourceLoadClass, ResolvableType type);
/**
* Access to field backed by {@link ResolvableType}.
*/
public static class ResolvableTypes {
public List<ExampleObject> listOfExampleObject;
public ExampleObject[] arrayOfExampleObject;
public Map<String, ExampleObject> mapOfExampleObject;
public static ResolvableType get(String name) {
Field field = ReflectionUtils.findField(ResolvableTypes.class, name);
return ResolvableType.forField(field);
}
}
}

View File

@@ -0,0 +1,97 @@
/*
* Copyright 2012-2016 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
*
* http://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.json;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link BasicJsonTester}.
*
* @author Phillip Webb
*/
public class BasicJsonTesterTests {
private static final String JSON = "{\"spring\":[\"boot\",\"framework\"]}";
@Rule
public ExpectedException thrown = ExpectedException.none();
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
private BasicJsonTester json = new BasicJsonTester(getClass());
@Test
public void createWhenResourceLoadClassIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ResourceLoadClass must not be null");
new BasicJsonTester(null);
}
@Test
public void fromJsonStringShouldReturnJsonContent() throws Exception {
assertThat(this.json.from(JSON)).isEqualToJson("source.json");
}
@Test
public void fromResourceStringShouldReturnJsonContent() throws Exception {
assertThat(this.json.from("source.json")).isEqualToJson(JSON);
}
@Test
public void fromResourceStringWithClassShouldReturnJsonContent() throws Exception {
assertThat(this.json.from("source.json", getClass())).isEqualToJson(JSON);
}
@Test
public void fromByteArrayShouldReturnJsonContent() throws Exception {
assertThat(this.json.from(JSON.getBytes())).isEqualToJson("source.json");
}
@Test
public void fromFileShouldReturnJsonContent() throws Exception {
File file = this.tempFolder.newFile("file.json");
FileCopyUtils.copy(JSON.getBytes(), file);
assertThat(this.json.from(file)).isEqualToJson("source.json");
}
@Test
public void fromInputStreamShouldReturnJsonContent() throws Exception {
InputStream inputStream = new ByteArrayInputStream(JSON.getBytes());
assertThat(this.json.from(inputStream)).isEqualToJson("source.json");
}
@Test
public void fromResourceShouldReturnJsonContent() throws Exception {
Resource resource = new ByteArrayResource(JSON.getBytes());
assertThat(this.json.from(resource)).isEqualToJson("source.json");
}
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright 2012-2017 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
*
* http://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.json;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.testsupport.runner.classpath.ClassPathOverrides;
import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link DuplicateJsonObjectContextCustomizerFactory}.
*
* @author Andy Wilkinson
*/
@RunWith(ModifiedClassPathRunner.class)
@ClassPathOverrides("org.json:json:20140107")
public class DuplicateJsonObjectContextCustomizerFactoryTests {
@Rule
public OutputCapture output = new OutputCapture();
@Test
public void warningForMultipleVersions() {
new DuplicateJsonObjectContextCustomizerFactory()
.createContextCustomizer(null, null).customizeContext(null, null);
assertThat(this.output.toString()).contains(
"Found multiple occurrences of org.json.JSONObject on the class path:");
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright 2012-2017 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
*
* http://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.json;
import org.springframework.util.ObjectUtils;
/**
* Example object used for serialization.
*/
public class ExampleObject {
private String name;
private int age;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != getClass()) {
return false;
}
ExampleObject other = (ExampleObject) obj;
return ObjectUtils.nullSafeEquals(this.name, other.name)
&& ObjectUtils.nullSafeEquals(this.age, other.age);
}
@Override
public String toString() {
return this.name + " " + this.age;
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright 2012-2017 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
*
* http://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.json;
import com.fasterxml.jackson.annotation.JsonView;
import org.springframework.util.ObjectUtils;
/**
* Example object used for serialization/deserialization with view.
*
* @author Madhura Bhave
*/
public class ExampleObjectWithView {
@JsonView(TestView.class)
private String name;
private int age;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != getClass()) {
return false;
}
ExampleObjectWithView other = (ExampleObjectWithView) obj;
return ObjectUtils.nullSafeEquals(this.name, other.name)
&& ObjectUtils.nullSafeEquals(this.age, other.age);
}
@Override
public String toString() {
return this.name + " " + this.age;
}
static class TestView {
}
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright 2012-2017 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
*
* http://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.json;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import org.springframework.core.ResolvableType;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link GsonTester}.
*
* @author Phillip Webb
*/
public class GsonTesterTests extends AbstractJsonMarshalTesterTests {
@Test
public void initFieldsWhenTestIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("TestInstance must not be null");
GsonTester.initFields(null, new GsonBuilder().create());
}
@Test
public void initFieldsWhenMarshallerIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Marshaller must not be null");
GsonTester.initFields(new InitFieldsTestClass(), (Gson) null);
}
@Test
public void initFieldsShouldSetNullFields() {
InitFieldsTestClass test = new InitFieldsTestClass();
assertThat(test.test).isNull();
assertThat(test.base).isNull();
GsonTester.initFields(test, new GsonBuilder().create());
assertThat(test.test).isNotNull();
assertThat(test.base).isNotNull();
assertThat(test.test.getType().resolve()).isEqualTo(List.class);
assertThat(test.test.getType().resolveGeneric()).isEqualTo(ExampleObject.class);
}
@Override
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass,
ResolvableType type) {
return new GsonTester<>(resourceLoadClass, type, new GsonBuilder().create());
}
static abstract class InitFieldsBaseClass {
public GsonTester<ExampleObject> base;
public GsonTester<ExampleObject> baseSet = new GsonTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
new GsonBuilder().create());
}
static class InitFieldsTestClass extends InitFieldsBaseClass {
public GsonTester<List<ExampleObject>> test;
public GsonTester<ExampleObject> testSet = new GsonTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
new GsonBuilder().create());
}
}

View File

@@ -0,0 +1,116 @@
/*
* Copyright 2012-2017 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
*
* http://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.json;
import java.io.Reader;
import java.io.StringReader;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ByteArrayResource;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for {@link JacksonTester}. Shows typical usage.
*
* @author Phillip Webb
* @author Madhura Bhave
*/
public class JacksonTesterIntegrationTests {
private JacksonTester<ExampleObject> simpleJson;
private JacksonTester<ExampleObjectWithView> jsonWithView;
private JacksonTester<List<ExampleObject>> listJson;
private JacksonTester<Map<String, Integer>> mapJson;
private ObjectMapper objectMapper;
private static final String JSON = "{\"name\":\"Spring\",\"age\":123}";
@Before
public void setup() {
this.objectMapper = new ObjectMapper();
JacksonTester.initFields(this, this.objectMapper);
}
@Test
public void typicalTest() throws Exception {
String example = JSON;
assertThat(this.simpleJson.parse(example).getObject().getName())
.isEqualTo("Spring");
}
@Test
public void typicalListTest() throws Exception {
String example = "[" + JSON + "]";
assertThat(this.listJson.parse(example)).asList().hasSize(1);
assertThat(this.listJson.parse(example).getObject().get(0).getName())
.isEqualTo("Spring");
}
@Test
public void typicalMapTest() throws Exception {
Map<String, Integer> map = new LinkedHashMap<>();
map.put("a", 1);
map.put("b", 2);
assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a")
.isEqualTo(1);
}
@Test
public void writeWithView() throws Exception {
this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
ExampleObjectWithView object = new ExampleObjectWithView();
object.setName("Spring");
object.setAge(123);
JsonContent<ExampleObjectWithView> content = this.jsonWithView
.forView(ExampleObjectWithView.TestView.class).write(object);
assertThat(content).extractingJsonPathStringValue("@.name").isEqualTo("Spring");
assertThat(content).doesNotHaveJsonPathValue("age");
}
@Test
public void readWithResourceAndView() throws Exception {
this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
ByteArrayResource resource = new ByteArrayResource(JSON.getBytes());
ObjectContent<ExampleObjectWithView> content = this.jsonWithView
.forView(ExampleObjectWithView.TestView.class).read(resource);
assertThat(content.getObject().getName()).isEqualTo("Spring");
assertThat(content.getObject().getAge()).isEqualTo(0);
}
@Test
public void readWithReaderAndView() throws Exception {
this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
Reader reader = new StringReader(JSON);
ObjectContent<ExampleObjectWithView> content = this.jsonWithView
.forView(ExampleObjectWithView.TestView.class).read(reader);
assertThat(content.getObject().getName()).isEqualTo("Spring");
assertThat(content.getObject().getAge()).isEqualTo(0);
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright 2012-2017 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
*
* http://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.json;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.springframework.core.ResolvableType;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link JacksonTester}.
*
* @author Phillip Webb
*/
public class JacksonTesterTests extends AbstractJsonMarshalTesterTests {
@Test
public void initFieldsWhenTestIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("TestInstance must not be null");
JacksonTester.initFields(null, new ObjectMapper());
}
@Test
public void initFieldsWhenMarshallerIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Marshaller must not be null");
JacksonTester.initFields(new InitFieldsTestClass(), (ObjectMapper) null);
}
@Test
public void initFieldsShouldSetNullFields() {
InitFieldsTestClass test = new InitFieldsTestClass();
assertThat(test.test).isNull();
assertThat(test.base).isNull();
JacksonTester.initFields(test, new ObjectMapper());
assertThat(test.test).isNotNull();
assertThat(test.base).isNotNull();
assertThat(test.test.getType().resolve()).isEqualTo(List.class);
assertThat(test.test.getType().resolveGeneric()).isEqualTo(ExampleObject.class);
}
@Override
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass,
ResolvableType type) {
return new JacksonTester<>(resourceLoadClass, type, new ObjectMapper());
}
static abstract class InitFieldsBaseClass {
public JacksonTester<ExampleObject> base;
public JacksonTester<ExampleObject> baseSet = new JacksonTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
new ObjectMapper());
}
static class InitFieldsTestClass extends InitFieldsBaseClass {
public JacksonTester<List<ExampleObject>> test;
public JacksonTester<ExampleObject> testSet = new JacksonTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
new ObjectMapper());
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright 2012-2017 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
*
* http://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.json;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.core.ResolvableType;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link JsonContent}.
*
* @author Phillip Webb
*/
public class JsonContentTests {
private static final String JSON = "{\"name\":\"spring\", \"age\":100}";
private static final ResolvableType TYPE = ResolvableType
.forClass(ExampleObject.class);
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void createWhenResourceLoadClassIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ResourceLoadClass must not be null");
new JsonContent<ExampleObject>(null, TYPE, JSON);
}
@Test
public void createWhenJsonIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("JSON must not be null");
new JsonContent<ExampleObject>(getClass(), TYPE, null);
}
@Test
public void createWhenTypeIsNullShouldCreateContent() throws Exception {
JsonContent<ExampleObject> content = new JsonContent<>(getClass(), null, JSON);
assertThat(content).isNotNull();
}
@Test
@SuppressWarnings("deprecation")
public void assertThatShouldReturnJsonContentAssert() throws Exception {
JsonContent<ExampleObject> content = new JsonContent<>(getClass(), TYPE, JSON);
assertThat(content.assertThat()).isInstanceOf(JsonContentAssert.class);
}
@Test
public void getJsonShouldReturnJson() throws Exception {
JsonContent<ExampleObject> content = new JsonContent<>(getClass(), TYPE, JSON);
assertThat(content.getJson()).isEqualTo(JSON);
}
@Test
public void toStringWhenHasTypeShouldReturnString() throws Exception {
JsonContent<ExampleObject> content = new JsonContent<>(getClass(), TYPE, JSON);
assertThat(content.toString())
.isEqualTo("JsonContent " + JSON + " created from " + TYPE);
}
@Test
public void toStringWhenHasNoTypeShouldReturnString() throws Exception {
JsonContent<ExampleObject> content = new JsonContent<>(getClass(), null, JSON);
assertThat(content.toString()).isEqualTo("JsonContent " + JSON);
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright 2012-2017 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
*
* http://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.json;
import java.util.List;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import org.junit.Test;
import org.springframework.core.ResolvableType;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link JsonbTester}.
*
* @author Eddú Meléndez
*/
public class JsonbTesterTests extends AbstractJsonMarshalTesterTests {
@Test
public void initFieldsWhenTestIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("TestInstance must not be null");
JsonbTester.initFields(null, JsonbBuilder.create());
}
@Test
public void initFieldsWhenMarshallerIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Marshaller must not be null");
JsonbTester.initFields(new InitFieldsTestClass(), (Jsonb) null);
}
@Test
public void initFieldsShouldSetNullFields() {
InitFieldsTestClass test = new InitFieldsTestClass();
assertThat(test.test).isNull();
assertThat(test.base).isNull();
JsonbTester.initFields(test, JsonbBuilder.create());
assertThat(test.test).isNotNull();
assertThat(test.base).isNotNull();
assertThat(test.test.getType().resolve()).isEqualTo(List.class);
assertThat(test.test.getType().resolveGeneric()).isEqualTo(ExampleObject.class);
}
@Override
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass,
ResolvableType type) {
return new JsonbTester<>(resourceLoadClass, type, JsonbBuilder.create());
}
static abstract class InitFieldsBaseClass {
public JsonbTester<ExampleObject> base;
public JsonbTester<ExampleObject> baseSet = new JsonbTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
JsonbBuilder.create());
}
static class InitFieldsTestClass extends InitFieldsBaseClass {
public JsonbTester<List<ExampleObject>> test;
public JsonbTester<ExampleObject> testSet = new JsonbTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
JsonbBuilder.create());
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright 2012-2017 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
*
* http://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.json;
import java.util.Collections;
import java.util.Map;
import org.assertj.core.api.AssertProvider;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ObjectContentAssert}.
*
* @author Phillip Webb
*/
public class ObjectContentAssertTests {
private static final ExampleObject SOURCE = new ExampleObject();
private static final ExampleObject DIFFERENT;
static {
DIFFERENT = new ExampleObject();
DIFFERENT.setAge(123);
}
@Test
public void isEqualToWhenObjectsAreEqualShouldPass() throws Exception {
assertThat(forObject(SOURCE)).isEqualTo(SOURCE);
}
@Test(expected = AssertionError.class)
public void isEqualToWhenObjectsAreDifferentShouldFail() throws Exception {
assertThat(forObject(SOURCE)).isEqualTo(DIFFERENT);
}
@Test
public void asArrayForArrayShouldReturnObjectArrayAssert() throws Exception {
ExampleObject[] source = new ExampleObject[] { SOURCE };
assertThat(forObject(source)).asArray().containsExactly(SOURCE);
}
@Test(expected = AssertionError.class)
public void asArrayForNonArrayShouldFail() throws Exception {
assertThat(forObject(SOURCE)).asArray();
}
@Test
public void asMapForMapShouldReturnMapAssert() throws Exception {
Map<String, ExampleObject> source = Collections.singletonMap("a", SOURCE);
assertThat(forObject(source)).asMap().containsEntry("a", SOURCE);
}
@Test(expected = AssertionError.class)
public void asMapForNonMapShouldFail() throws Exception {
assertThat(forObject(SOURCE)).asMap();
}
private AssertProvider<ObjectContentAssert<Object>> forObject(final Object source) {
return () -> new ObjectContentAssert<>(source);
}
}

View File

@@ -0,0 +1,80 @@
/*
* Copyright 2012-2017 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
*
* http://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.json;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.core.ResolvableType;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ObjectContent}.
*
* @author Phillip Webb
*/
public class ObjectContentTests {
private static final ExampleObject OBJECT = new ExampleObject();
private static final ResolvableType TYPE = ResolvableType
.forClass(ExampleObject.class);
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void createWhenObjectIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Object must not be null");
new ObjectContent<ExampleObject>(TYPE, null);
}
@Test
public void createWhenTypeIsNullShouldCreateContent() throws Exception {
ObjectContent<ExampleObject> content = new ObjectContent<>(null, OBJECT);
assertThat(content).isNotNull();
}
@Test
public void assertThatShouldReturnObjectContentAssert() throws Exception {
ObjectContent<ExampleObject> content = new ObjectContent<>(TYPE, OBJECT);
assertThat(content.assertThat()).isInstanceOf(ObjectContentAssert.class);
}
@Test
public void getObjectShouldReturnObject() throws Exception {
ObjectContent<ExampleObject> content = new ObjectContent<>(TYPE, OBJECT);
assertThat(content.getObject()).isEqualTo(OBJECT);
}
@Test
public void toStringWhenHasTypeShouldReturnString() throws Exception {
ObjectContent<ExampleObject> content = new ObjectContent<>(TYPE, OBJECT);
assertThat(content.toString())
.isEqualTo("ObjectContent " + OBJECT + " created from " + TYPE);
}
@Test
public void toStringWhenHasNoTypeShouldReturnString() throws Exception {
ObjectContent<ExampleObject> content = new ObjectContent<>(null, OBJECT);
assertThat(content.toString()).isEqualTo("ObjectContent " + OBJECT);
}
}

View File

@@ -0,0 +1,316 @@
/*
* Copyright 2012-2017 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
*
* http://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.mock.mockito;
import java.util.ArrayList;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Answers;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.mock.mockito.example.ExampleExtraInterface;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.boot.test.mock.mockito.example.RealExampleService;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link DefinitionsParser}.
*
* @author Phillip Webb
*/
public class DefinitionsParserTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private DefinitionsParser parser = new DefinitionsParser();
@Test
public void parseSingleMockBean() {
this.parser.parse(SingleMockBean.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getMockDefinition(0).getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
}
@Test
public void parseRepeatMockBean() {
this.parser.parse(RepeatMockBean.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getMockDefinition(0).getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
assertThat(getMockDefinition(1).getTypeToMock().resolve())
.isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseMockBeanAttributes() throws Exception {
this.parser.parse(MockBeanAttributes.class);
assertThat(getDefinitions()).hasSize(1);
MockDefinition definition = getMockDefinition(0);
assertThat(definition.getName()).isEqualTo("Name");
assertThat(definition.getTypeToMock().resolve()).isEqualTo(ExampleService.class);
assertThat(definition.getExtraInterfaces())
.containsExactly(ExampleExtraInterface.class);
assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS);
assertThat(definition.isSerializable()).isEqualTo(true);
assertThat(definition.getReset()).isEqualTo(MockReset.NONE);
assertThat(definition.getQualifier()).isNull();
}
@Test
public void parseMockBeanOnClassAndField() throws Exception {
this.parser.parse(MockBeanOnClassAndField.class);
assertThat(getDefinitions()).hasSize(2);
MockDefinition classDefinition = getMockDefinition(0);
assertThat(classDefinition.getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
assertThat(classDefinition.getQualifier()).isNull();
MockDefinition fieldDefinition = getMockDefinition(1);
assertThat(fieldDefinition.getTypeToMock().resolve())
.isEqualTo(ExampleServiceCaller.class);
QualifierDefinition qualifier = QualifierDefinition.forElement(
ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller"));
assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier);
}
@Test
public void parseMockBeanInferClassToMock() throws Exception {
this.parser.parse(MockBeanInferClassToMock.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getMockDefinition(0).getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
}
@Test
public void parseMockBeanMissingClassToMock() throws Exception {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Unable to deduce type to mock");
this.parser.parse(MockBeanMissingClassToMock.class);
}
@Test
public void parseMockBeanMultipleClasses() throws Exception {
this.parser.parse(MockBeanMultipleClasses.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getMockDefinition(0).getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
assertThat(getMockDefinition(1).getTypeToMock().resolve())
.isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseMockBeanMultipleClassesWithName() throws Exception {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage(
"The name attribute can only be used when mocking a single class");
this.parser.parse(MockBeanMultipleClassesWithName.class);
}
@Test
public void parseSingleSpyBean() {
this.parser.parse(SingleSpyBean.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
}
@Test
public void parseRepeatSpyBean() {
this.parser.parse(RepeatSpyBean.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
assertThat(getSpyDefinition(1).getTypeToSpy().resolve())
.isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseSpyBeanAttributes() throws Exception {
this.parser.parse(SpyBeanAttributes.class);
assertThat(getDefinitions()).hasSize(1);
SpyDefinition definition = getSpyDefinition(0);
assertThat(definition.getName()).isEqualTo("Name");
assertThat(definition.getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
assertThat(definition.getReset()).isEqualTo(MockReset.NONE);
assertThat(definition.getQualifier()).isNull();
}
@Test
public void parseSpyBeanOnClassAndField() throws Exception {
this.parser.parse(SpyBeanOnClassAndField.class);
assertThat(getDefinitions()).hasSize(2);
SpyDefinition classDefinition = getSpyDefinition(0);
assertThat(classDefinition.getQualifier()).isNull();
assertThat(classDefinition.getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
SpyDefinition fieldDefinition = getSpyDefinition(1);
QualifierDefinition qualifier = QualifierDefinition.forElement(
ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller"));
assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier);
assertThat(fieldDefinition.getTypeToSpy().resolve())
.isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseSpyBeanInferClassToMock() throws Exception {
this.parser.parse(SpyBeanInferClassToMock.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
}
@Test
public void parseSpyBeanMissingClassToMock() throws Exception {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Unable to deduce type to spy");
this.parser.parse(SpyBeanMissingClassToMock.class);
}
@Test
public void parseSpyBeanMultipleClasses() throws Exception {
this.parser.parse(SpyBeanMultipleClasses.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
assertThat(getSpyDefinition(1).getTypeToSpy().resolve())
.isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseSpyBeanMultipleClassesWithName() throws Exception {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage(
"The name attribute can only be used when spying a single class");
this.parser.parse(SpyBeanMultipleClassesWithName.class);
}
private MockDefinition getMockDefinition(int index) {
return (MockDefinition) getDefinitions().get(index);
}
private SpyDefinition getSpyDefinition(int index) {
return (SpyDefinition) getDefinitions().get(index);
}
private List<Definition> getDefinitions() {
return new ArrayList<>(this.parser.getDefinitions());
}
@MockBean(ExampleService.class)
static class SingleMockBean {
}
@MockBeans({ @MockBean(ExampleService.class), @MockBean(ExampleServiceCaller.class) })
static class RepeatMockBean {
}
@MockBean(name = "Name", classes = ExampleService.class, extraInterfaces = ExampleExtraInterface.class, answer = Answers.RETURNS_SMART_NULLS, serializable = true, reset = MockReset.NONE)
static class MockBeanAttributes {
}
@MockBean(ExampleService.class)
static class MockBeanOnClassAndField {
@MockBean(ExampleServiceCaller.class)
@Qualifier("test")
private Object caller;
}
@MockBean({ ExampleService.class, ExampleServiceCaller.class })
static class MockBeanMultipleClasses {
}
@MockBean(name = "name", classes = { ExampleService.class,
ExampleServiceCaller.class })
static class MockBeanMultipleClassesWithName {
}
static class MockBeanInferClassToMock {
@MockBean
private ExampleService exampleService;
}
@MockBean
static class MockBeanMissingClassToMock {
}
@SpyBean(RealExampleService.class)
static class SingleSpyBean {
}
@SpyBeans({ @SpyBean(RealExampleService.class),
@SpyBean(ExampleServiceCaller.class) })
static class RepeatSpyBean {
}
@SpyBean(name = "Name", classes = RealExampleService.class, reset = MockReset.NONE)
static class SpyBeanAttributes {
}
@SpyBean(RealExampleService.class)
static class SpyBeanOnClassAndField {
@SpyBean(ExampleServiceCaller.class)
@Qualifier("test")
private Object caller;
}
@SpyBean({ RealExampleService.class, ExampleServiceCaller.class })
static class SpyBeanMultipleClasses {
}
@SpyBean(name = "name", classes = { RealExampleService.class,
ExampleServiceCaller.class })
static class SpyBeanMultipleClassesWithName {
}
static class SpyBeanInferClassToMock {
@SpyBean
private RealExampleService exampleService;
}
@SpyBean
static class SpyBeanMissingClassToMock {
}
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright 2012-2017 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Test {@link MockBean} for a factory bean.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
public class MockBeanForBeanFactoryIntegrationTests {
// gh-7439
@MockBean
private TestFactoryBean testFactoryBean;
@Autowired
private ApplicationContext applicationContext;
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testName() throws Exception {
TestBean testBean = mock(TestBean.class);
given(testBean.hello()).willReturn("amock");
given(this.testFactoryBean.getObjectType()).willReturn((Class) TestBean.class);
given(this.testFactoryBean.getObject()).willReturn(testBean);
TestBean bean = this.applicationContext.getBean(TestBean.class);
assertThat(bean.hello()).isEqualTo("amock");
}
@Configuration
static class Config {
@Bean
public TestFactoryBean testFactoryBean() {
return new TestFactoryBean();
}
}
static class TestFactoryBean implements FactoryBean<TestBean> {
@Override
public TestBean getObject() throws Exception {
return () -> "normal";
}
@Override
public Class<?> getObjectType() {
return TestBean.class;
}
@Override
public boolean isSingleton() {
return false;
}
}
interface TestBean {
String hello();
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.boot.test.mock.mockito.example.FailingExampleService;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Test {@link MockBean} on a configuration class can be used to replace existing beans.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
public class MockBeanOnConfigurationClassForExistingBeanIntegrationTests {
@Autowired
private ExampleServiceCaller caller;
@Test
public void testMocking() throws Exception {
given(this.caller.getService().greeting()).willReturn("Boot");
assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot");
}
@Configuration
@MockBean(ExampleService.class)
@Import({ ExampleServiceCaller.class, FailingExampleService.class })
static class Config {
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Test {@link MockBean} on a configuration class can be used to inject new mock
* instances.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
public class MockBeanOnConfigurationClassForNewBeanIntegrationTests {
@Autowired
private ExampleServiceCaller caller;
@Test
public void testMocking() throws Exception {
given(this.caller.getService().greeting()).willReturn("Boot");
assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot");
}
@Configuration
@MockBean(ExampleService.class)
@Import(ExampleServiceCaller.class)
static class Config {
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.boot.test.mock.mockito.example.FailingExampleService;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Test {@link MockBean} on a field on a {@code @Configuration} class can be used to
* replace existing beans.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
public class MockBeanOnConfigurationFieldForExistingBeanIntegrationTests {
@Autowired
private Config config;
@Autowired
private ExampleServiceCaller caller;
@Test
public void testMocking() throws Exception {
given(this.config.exampleService.greeting()).willReturn("Boot");
assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot");
}
@Configuration
@Import({ ExampleServiceCaller.class, FailingExampleService.class })
static class Config {
@MockBean
private ExampleService exampleService;
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Test {@link MockBean} on a field on a {@code @Configuration} class can be used to
* inject new mock instances.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
public class MockBeanOnConfigurationFieldForNewBeanIntegrationTests {
@Autowired
private Config config;
@Autowired
private ExampleServiceCaller caller;
@Test
public void testMocking() throws Exception {
given(this.config.exampleService.greeting()).willReturn("Boot");
assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot");
}
@Configuration
@Import(ExampleServiceCaller.class)
static class Config {
@MockBean
private ExampleService exampleService;
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBeanOnContextHierarchyIntegrationTests.ChildConfig;
import org.springframework.boot.test.mock.mockito.MockBeanOnContextHierarchyIntegrationTests.ParentConfig;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test {@link MockBean} can be used with a {@link ContextHierarchy}.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@ContextHierarchy({ @ContextConfiguration(classes = ParentConfig.class),
@ContextConfiguration(classes = ChildConfig.class) })
public class MockBeanOnContextHierarchyIntegrationTests {
@Autowired
private ChildConfig childConfig;
@Test
public void testMocking() throws Exception {
ApplicationContext context = this.childConfig.getContext();
ApplicationContext parentContext = context.getParent();
assertThat(parentContext.getBeanNamesForType(ExampleService.class)).hasSize(1);
assertThat(parentContext.getBeanNamesForType(ExampleServiceCaller.class))
.hasSize(0);
assertThat(context.getBeanNamesForType(ExampleService.class)).hasSize(0);
assertThat(context.getBeanNamesForType(ExampleServiceCaller.class)).hasSize(1);
assertThat(context.getBean(ExampleService.class)).isNotNull();
assertThat(context.getBean(ExampleServiceCaller.class)).isNotNull();
}
@Configuration
@MockBean(ExampleService.class)
static class ParentConfig {
}
@Configuration
@MockBean(ExampleServiceCaller.class)
static class ChildConfig implements ApplicationContextAware {
private ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context = applicationContext;
}
public ApplicationContext getContext() {
return this.context;
}
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.boot.test.mock.mockito.example.FailingExampleService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Test {@link MockBean} when used in combination with scoped proxy targets.
*
* @author Phillip Webb
* @see <a href="https://github.com/spring-projects/spring-boot/issues/5724">gh-5724</a>
*/
@RunWith(SpringRunner.class)
public class MockBeanOnScopedProxyTests {
@MockBean
private ExampleService exampleService;
@Autowired
private ExampleServiceCaller caller;
@Test
public void testMocking() throws Exception {
given(this.caller.getService().greeting()).willReturn("Boot");
assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot");
}
@Configuration
@Import({ ExampleServiceCaller.class })
static class Config {
@Bean
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public ExampleService exampleService() {
return new FailingExampleService();
}
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.boot.test.mock.mockito.example.FailingExampleService;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Test {@link MockBean} on a test class can be used to replace existing beans.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@MockBean(ExampleService.class)
public class MockBeanOnTestClassForExistingBeanIntegrationTests {
@Autowired
private ExampleServiceCaller caller;
@Test
public void testMocking() throws Exception {
given(this.caller.getService().greeting()).willReturn("Boot");
assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot");
}
@Configuration
@Import({ ExampleServiceCaller.class, FailingExampleService.class })
static class Config {
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Test {@link MockBean} on a test class can be used to inject new mock instances.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@MockBean(ExampleService.class)
public class MockBeanOnTestClassForNewBeanIntegrationTests {
@Autowired
private ExampleServiceCaller caller;
@Test
public void testMocking() throws Exception {
given(this.caller.getService().greeting()).willReturn("Boot");
assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot");
}
@Configuration
@Import(ExampleServiceCaller.class)
static class Config {
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Test {@link MockBean} on a test class field can be used to replace existing beans when
* the context is cached. This test is identical to
* {@link MockBeanOnTestFieldForExistingBeanIntegrationTests} so one of them should
* trigger application context caching.
*
* @author Phillip Webb
* @see MockBeanOnTestFieldForExistingBeanIntegrationTests
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MockBeanOnTestFieldForExistingBeanConfig.class)
public class MockBeanOnTestFieldForExistingBeanCacheIntegrationTests {
@MockBean
private ExampleService exampleService;
@Autowired
private ExampleServiceCaller caller;
@Test
public void testMocking() throws Exception {
given(this.exampleService.greeting()).willReturn("Boot");
assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot");
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.boot.test.mock.mockito.example.FailingExampleService;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Config for {@link MockBeanOnTestFieldForExistingBeanIntegrationTests} and
* {@link MockBeanOnTestFieldForExistingBeanCacheIntegrationTests}. Extracted to a shared
* config to trigger caching.
*
* @author Phillip Webb
*/
@Configuration
@Import({ ExampleServiceCaller.class, FailingExampleService.class })
public class MockBeanOnTestFieldForExistingBeanConfig {
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Test {@link MockBean} on a test class field can be used to replace existing beans.
*
* @author Phillip Webb
* @see MockBeanOnTestFieldForExistingBeanCacheIntegrationTests
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MockBeanOnTestFieldForExistingBeanConfig.class)
public class MockBeanOnTestFieldForExistingBeanIntegrationTests {
@MockBean
private ExampleService exampleService;
@Autowired
private ExampleServiceCaller caller;
@Test
public void testMocking() throws Exception {
given(this.exampleService.greeting()).willReturn("Boot");
assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot");
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.example.CustomQualifier;
import org.springframework.boot.test.mock.mockito.example.CustomQualifierExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.boot.test.mock.mockito.example.RealExampleService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
/**
* Test {@link MockBean} on a test class field can be used to replace existing bean while
* preserving qualifiers.
*
* @author Stephane Nicoll
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
public class MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests {
@MockBean
@CustomQualifier
private ExampleService service;
@Autowired
private ExampleServiceCaller caller;
@Autowired
private ApplicationContext applicationContext;
@Test
public void testMocking() throws Exception {
this.caller.sayGreeting();
verify(this.service).greeting();
}
@Test
public void onlyQualifiedBeanIsReplaced() {
assertThat(this.applicationContext.getBean("service")).isSameAs(this.service);
ExampleService anotherService = this.applicationContext.getBean("anotherService",
ExampleService.class);
assertThat(anotherService.greeting()).isEqualTo("Another");
}
@Configuration
static class TestConfig {
@Bean
public CustomQualifierExampleService service() {
return new CustomQualifierExampleService();
}
@Bean
public ExampleService anotherService() {
return new RealExampleService("Another");
}
@Bean
public ExampleServiceCaller controller(@CustomQualifier ExampleService service) {
return new ExampleServiceCaller(service);
}
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Test {@link MockBean} on a test class field can be used to inject new mock instances.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
public class MockBeanOnTestFieldForNewBeanIntegrationTests {
@MockBean
private ExampleService exampleService;
@Autowired
private ExampleServiceCaller caller;
@Test
public void testMocking() throws Exception {
given(this.exampleService.greeting()).willReturn("Boot");
assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot");
}
@Configuration
@Import(ExampleServiceCaller.class)
static class Config {
}
}

View File

@@ -0,0 +1,99 @@
/*
* Copyright 2012-2017 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
*
* http://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.mock.mockito;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.SimpleCacheResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Test {@link MockBean} when mixed with Spring AOP.
*
* @author Phillip Webb
* @see <a href="https://github.com/spring-projects/spring-boot/issues/5837">5837</a>
*/
@RunWith(SpringRunner.class)
public class MockBeanWithAopProxyTests {
@MockBean
private DateService dateService;
@Test
public void verifyShouldUseProxyTarget() throws Exception {
given(this.dateService.getDate(false)).willReturn(1L);
Long d1 = this.dateService.getDate(false);
assertThat(d1).isEqualTo(1L);
given(this.dateService.getDate(false)).willReturn(2L);
Long d2 = this.dateService.getDate(false);
assertThat(d2).isEqualTo(2L);
verify(this.dateService, times(2)).getDate(false);
verify(this.dateService, times(2)).getDate(eq(false));
verify(this.dateService, times(2)).getDate(anyBoolean());
}
@Configuration
@EnableCaching(proxyTargetClass = true)
@Import(DateService.class)
static class Config {
@Bean
public CacheResolver cacheResolver(CacheManager cacheManager) {
SimpleCacheResolver resolver = new SimpleCacheResolver();
resolver.setCacheManager(cacheManager);
return resolver;
}
@Bean
public ConcurrentMapCacheManager cacheManager() {
ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager();
cacheManager.setCacheNames(Arrays.asList("test"));
return cacheManager;
}
}
@Service
static class DateService {
@Cacheable(cacheNames = "test")
public Long getDate(boolean argument) {
return System.nanoTime();
}
}
}

View File

@@ -0,0 +1,84 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Tests for a mock bean where the mocked interface has an async method.
*
* @author Andy Wilkinson
*/
@RunWith(SpringRunner.class)
public class MockBeanWithAsyncInterfaceMethodIntegrationTests {
@MockBean
private Transformer transformer;
@Autowired
private MyService service;
@Test
public void mockedMethodsAreNotAsync() {
given(this.transformer.transform("foo")).willReturn("bar");
assertThat(this.service.transform("foo")).isEqualTo("bar");
}
private interface Transformer {
@Async
String transform(String input);
}
private static class MyService {
private final Transformer transformer;
MyService(Transformer transformer) {
this.transformer = transformer;
}
public String transform(String input) {
return this.transformer.transform(input);
}
}
@Configuration
@EnableAsync
static class MyConfiguration {
@Bean
public MyService myService(Transformer transformer) {
return new MyService(transformer);
}
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.example.ExampleGenericService;
import org.springframework.boot.test.mock.mockito.example.ExampleGenericServiceCaller;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Test {@link MockBean} on a test class field can be used to inject new mock instances.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
public class MockBeanWithGenericsOnTestFieldForNewBeanIntegrationTests {
@MockBean
private ExampleGenericService<Integer> exampleIntegerService;
@MockBean
private ExampleGenericService<String> exampleStringService;
@Autowired
private ExampleGenericServiceCaller caller;
@Test
public void testMocking() throws Exception {
given(this.exampleIntegerService.greeting()).willReturn(200);
given(this.exampleStringService.greeting()).willReturn("Boot");
assertThat(this.caller.sayGreeting()).isEqualTo("I say 200 Boot");
}
@Configuration
@Import(ExampleGenericServiceCaller.class)
static class Config {
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Tests for a mock bean where the class being mocked uses field injection.
*
* @author Andy Wilkinson
*/
@RunWith(SpringRunner.class)
public class MockBeanWithInjectedFieldIntegrationTests {
@MockBean
private MyService myService;
@Test
public void fieldInjectionIntoMyServiceMockIsNotAttempted() {
given(this.myService.getCount()).willReturn(5);
assertThat(this.myService.getCount()).isEqualTo(5);
}
private static class MyService {
@Autowired
private MyRepository repository;
public int getCount() {
return this.repository.findAll().size();
}
}
private interface MyRepository {
List<Object> findAll();
}
}

View File

@@ -0,0 +1,99 @@
/*
* Copyright 2012-2017 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
*
* http://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.mock.mockito;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Answers;
import org.mockito.Mockito;
import org.mockito.mock.MockCreationSettings;
import org.springframework.boot.test.mock.mockito.example.ExampleExtraInterface;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.core.ResolvableType;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link MockDefinition}.
*
* @author Phillip Webb
*/
public class MockDefinitionTests {
private static final ResolvableType EXAMPLE_SERVICE_TYPE = ResolvableType
.forClass(ExampleService.class);
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void classToMockMustNotBeNull() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("TypeToMock must not be null");
new MockDefinition(null, null, null, null, false, null, null);
}
@Test
public void createWithDefaults() throws Exception {
MockDefinition definition = new MockDefinition(null, EXAMPLE_SERVICE_TYPE, null,
null, false, null, null);
assertThat(definition.getName()).isNull();
assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE);
assertThat(definition.getExtraInterfaces()).isEmpty();
assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_DEFAULTS);
assertThat(definition.isSerializable()).isFalse();
assertThat(definition.getReset()).isEqualTo(MockReset.AFTER);
assertThat(definition.getQualifier()).isNull();
}
@Test
public void createExplicit() throws Exception {
QualifierDefinition qualifier = mock(QualifierDefinition.class);
MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE,
new Class<?>[] { ExampleExtraInterface.class },
Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, qualifier);
assertThat(definition.getName()).isEqualTo("name");
assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE);
assertThat(definition.getExtraInterfaces())
.containsExactly(ExampleExtraInterface.class);
assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS);
assertThat(definition.isSerializable()).isTrue();
assertThat(definition.getReset()).isEqualTo(MockReset.BEFORE);
assertThat(definition.isProxyTargetAware()).isFalse();
assertThat(definition.getQualifier()).isEqualTo(qualifier);
}
@Test
public void createMock() throws Exception {
MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE,
new Class<?>[] { ExampleExtraInterface.class },
Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, null);
ExampleService mock = definition.createMock();
MockCreationSettings<?> settings = Mockito.mockingDetails(mock)
.getMockCreationSettings();
assertThat(mock).isInstanceOf(ExampleService.class);
assertThat(mock).isInstanceOf(ExampleExtraInterface.class);
assertThat(settings.getMockName().toString()).isEqualTo("name");
assertThat(settings.getDefaultAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS);
assertThat(settings.isSerializable()).isTrue();
assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE);
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.withSettings;
/**
* Tests for {@link MockReset}.
*
* @author Phillip Webb
*/
public class MockResetTests {
@Test
public void noneAttachesReset() {
ExampleService mock = mock(ExampleService.class);
assertThat(MockReset.get(mock)).isEqualTo(MockReset.NONE);
}
@Test
public void withSettingsOfNoneAttachesReset() {
ExampleService mock = mock(ExampleService.class,
MockReset.withSettings(MockReset.NONE));
assertThat(MockReset.get(mock)).isEqualTo(MockReset.NONE);
}
@Test
public void beforeAttachesReset() {
ExampleService mock = mock(ExampleService.class, MockReset.before());
assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE);
}
@Test
public void afterAttachesReset() {
ExampleService mock = mock(ExampleService.class, MockReset.after());
assertThat(MockReset.get(mock)).isEqualTo(MockReset.AFTER);
}
@Test
public void withSettingsAttachesReset() {
ExampleService mock = mock(ExampleService.class,
MockReset.withSettings(MockReset.BEFORE));
assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE);
}
@Test
public void apply() throws Exception {
ExampleService mock = mock(ExampleService.class,
MockReset.apply(MockReset.AFTER, withSettings()));
assertThat(MockReset.get(mock)).isEqualTo(MockReset.AFTER);
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2012-2017 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
import org.junit.runner.notification.Failure;
import org.springframework.boot.testsupport.runner.classpath.ClassPathOverrides;
import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for compatibility with Mockito 2.5
*
* @author Andy Wilkinson
* @author Phillip Webb
*/
@RunWith(ModifiedClassPathRunner.class)
@ClassPathOverrides("org.mockito:mockito-core:2.5.4")
public class Mockito25Tests {
@Test
public void resetMocksTestExecutionListenerTestsWithMockito2() {
runTests(ResetMocksTestExecutionListenerTests.class);
}
@Test
public void spyBeanWithAopProxyTestsWithMockito2() {
runTests(SpyBeanWithAopProxyTests.class);
}
private void runTests(Class<?> testClass) {
Result result = new JUnitCore().run(testClass);
for (Failure failure : result.getFailures()) {
System.err.println(failure.getTrace());
}
assertThat(result.getFailureCount()).isEqualTo(0);
assertThat(result.getRunCount()).isGreaterThan(0);
}
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import org.springframework.test.context.ContextCustomizer;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link MockitoContextCustomizerFactory}.
*
* @author Phillip Webb
*/
public class MockitoContextCustomizerFactoryTests {
private final MockitoContextCustomizerFactory factory = new MockitoContextCustomizerFactory();
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void getContextCustomizerWithoutAnnotationReturnsCustomizer()
throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(NoMockBeanAnnotation.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void getContextCustomizerWithAnnotationReturnsCustomizer() throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(WithMockBeanAnnotation.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void getContextCustomizerUsesMocksAsCacheKey() throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(WithMockBeanAnnotation.class, null);
assertThat(customizer).isNotNull();
ContextCustomizer same = this.factory
.createContextCustomizer(WithSameMockBeanAnnotation.class, null);
assertThat(customizer).isNotNull();
ContextCustomizer different = this.factory
.createContextCustomizer(WithDifferentMockBeanAnnotation.class, null);
assertThat(different).isNotNull();
assertThat(customizer.hashCode()).isEqualTo(same.hashCode());
assertThat(customizer.hashCode()).isNotEqualTo(different.hashCode());
assertThat(customizer).isEqualTo(customizer);
assertThat(customizer).isEqualTo(same);
assertThat(customizer).isNotEqualTo(different);
}
static class NoMockBeanAnnotation {
}
@MockBean({ Service1.class, Service2.class })
static class WithMockBeanAnnotation {
}
@MockBean({ Service2.class, Service1.class })
static class WithSameMockBeanAnnotation {
}
@MockBean({ Service1.class })
static class WithDifferentMockBeanAnnotation {
}
interface Service1 {
}
interface Service2 {
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright 2012-2017 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
*
* http://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.mock.mockito;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.Test;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.core.ResolvableType;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link MockitoContextCustomizer}.
*
* @author Phillip Webb
*/
public class MockitoContextCustomizerTests {
private static final Set<MockDefinition> NO_DEFINITIONS = Collections.emptySet();
@Test
public void hashCodeAndEquals() {
MockDefinition d1 = createTestMockDefinition(ExampleService.class);
MockDefinition d2 = createTestMockDefinition(ExampleServiceCaller.class);
MockitoContextCustomizer c1 = new MockitoContextCustomizer(NO_DEFINITIONS);
MockitoContextCustomizer c2 = new MockitoContextCustomizer(
new LinkedHashSet<>(Arrays.asList(d1, d2)));
MockitoContextCustomizer c3 = new MockitoContextCustomizer(
new LinkedHashSet<>(Arrays.asList(d2, d1)));
assertThat(c2.hashCode()).isEqualTo(c3.hashCode());
assertThat(c1).isEqualTo(c1).isNotEqualTo(c2);
assertThat(c2).isEqualTo(c2).isEqualTo(c3).isNotEqualTo(c1);
}
private MockDefinition createTestMockDefinition(Class<?> typeToMock) {
return new MockDefinition(null, ResolvableType.forClass(typeToMock), null, null,
false, null, null);
}
}

View File

@@ -0,0 +1,167 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.FailingExampleService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link MockitoPostProcessor}. See also the integration tests.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class MockitoPostProcessorTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void cannotMockMultipleBeans() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
MockitoPostProcessor.register(context);
context.register(MultipleBeans.class);
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage(
"Unable to register mock bean " + ExampleService.class.getName()
+ " expected a single matching bean to replace "
+ "but found [example1, example2]");
context.refresh();
}
@Test
public void cannotMockMultipleQualifiedBeans() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
MockitoPostProcessor.register(context);
context.register(MultipleQualifiedBeans.class);
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage(
"Unable to register mock bean " + ExampleService.class.getName()
+ " expected a single matching bean to replace "
+ "but found [example1, example3]");
context.refresh();
}
@Test
public void canMockBeanProducedByFactoryBeanWithObjectTypeAttribute() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
MockitoPostProcessor.register(context);
RootBeanDefinition factoryBeanDefinition = new RootBeanDefinition(
TestFactoryBean.class);
factoryBeanDefinition.setAttribute("factoryBeanObjectType",
SomeInterface.class.getName());
context.registerBeanDefinition("beanToBeMocked", factoryBeanDefinition);
context.register(MockedFactoryBean.class);
context.refresh();
assertThat(Mockito.mockingDetails(context.getBean("beanToBeMocked")).isMock())
.isTrue();
}
@Configuration
@MockBean(SomeInterface.class)
static class MockedFactoryBean {
@Bean
public TestFactoryBean testFactoryBean() {
return new TestFactoryBean();
}
}
@Configuration
@MockBean(ExampleService.class)
static class MultipleBeans {
@Bean
public ExampleService example1() {
return new FailingExampleService();
}
@Bean
public ExampleService example2() {
return new FailingExampleService();
}
}
@Configuration
static class MultipleQualifiedBeans {
@MockBean(ExampleService.class)
@Qualifier("test")
private ExampleService mock;
@Bean
@Qualifier("test")
public ExampleService example1() {
return new FailingExampleService();
}
@Bean
public ExampleService example2() {
return new FailingExampleService();
}
@Bean
@Qualifier("test")
public ExampleService example3() {
return new FailingExampleService();
}
}
static class TestFactoryBean implements FactoryBean<Object> {
@Override
public Object getObject() throws Exception {
return new TestBean();
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return true;
}
}
interface SomeInterface {
}
static class TestBean implements SomeInterface {
}
}

View File

@@ -0,0 +1,107 @@
/*
* Copyright 2012-2017 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
*
* http://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.mock.mockito;
import java.io.InputStream;
import java.lang.reflect.Field;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.TestContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link MockitoTestExecutionListener}.
*
* @author Phillip Webb
*/
public class MockitoTestExecutionListenerTests {
private MockitoTestExecutionListener listener = new MockitoTestExecutionListener();
@Mock
private ApplicationContext applicationContext;
@Mock
private MockitoPostProcessor postProcessor;
@Captor
private ArgumentCaptor<Field> fieldCaptor;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
given(this.applicationContext.getBean(MockitoPostProcessor.class))
.willReturn(this.postProcessor);
}
@Test
public void prepareTestInstanceShouldInitMockitoAnnotations() throws Exception {
WithMockitoAnnotations instance = new WithMockitoAnnotations();
this.listener.prepareTestInstance(mockTestContext(instance));
assertThat(instance.mock).isNotNull();
assertThat(instance.captor).isNotNull();
}
@Test
public void prepareTestInstanceShouldInjectMockBean() throws Exception {
WithMockBean instance = new WithMockBean();
this.listener.prepareTestInstance(mockTestContext(instance));
verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance),
(MockDefinition) any());
assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean");
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private TestContext mockTestContext(Object instance) {
TestContext testContext = mock(TestContext.class);
given(testContext.getTestInstance()).willReturn(instance);
given(testContext.getTestClass()).willReturn((Class) instance.getClass());
given(testContext.getApplicationContext()).willReturn(this.applicationContext);
return testContext;
}
static class WithMockitoAnnotations {
@Mock
InputStream mock;
@Captor
ArgumentCaptor<InputStream> captor;
}
static class WithMockBean {
@MockBean
InputStream mockBean;
}
}

View File

@@ -0,0 +1,173 @@
/*
* Copyright 2012-2017 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
*
* http://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.mock.mockito;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link QualifierDefinition}.
*
* @author Phillip Webb
*/
public class QualifierDefinitionTests {
@Mock
private ConfigurableListableBeanFactory beanFactory;
@Captor
private ArgumentCaptor<DependencyDescriptor> descriptorCaptor;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void forElementFieldIsNullShouldReturnNull() throws Exception {
assertThat(QualifierDefinition.forElement((Field) null)).isNull();
}
@Test
public void forElementWhenElementIsNotFieldShouldReturnNull() throws Exception {
assertThat(QualifierDefinition.forElement(getClass())).isNull();
}
@Test
public void forElementWhenElementIsFieldWithNoQualifiersShouldReturnNull()
throws Exception {
QualifierDefinition definition = QualifierDefinition
.forElement(ReflectionUtils.findField(ConfigA.class, "noQualifier"));
assertThat(definition).isNull();
}
@Test
public void forElementWhenElementIsFieldWithQualifierShouldReturnDefinition()
throws Exception {
QualifierDefinition definition = QualifierDefinition
.forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier"));
assertThat(definition).isNotNull();
}
@Test
public void matchesShouldCallBeanFactory() throws Exception {
Field field = ReflectionUtils.findField(ConfigA.class, "directQualifier");
QualifierDefinition qualifierDefinition = QualifierDefinition.forElement(field);
qualifierDefinition.matches(this.beanFactory, "bean");
verify(this.beanFactory).isAutowireCandidate(eq("bean"),
this.descriptorCaptor.capture());
assertThat(this.descriptorCaptor.getValue().getAnnotatedElement())
.isEqualTo(field);
}
@Test
public void applyToShouldSetQualifierElement() throws Exception {
Field field = ReflectionUtils.findField(ConfigA.class, "directQualifier");
QualifierDefinition qualifierDefinition = QualifierDefinition.forElement(field);
RootBeanDefinition definition = new RootBeanDefinition();
qualifierDefinition.applyTo(definition);
assertThat(definition.getQualifiedElement()).isEqualTo(field);
}
@Test
public void hashCodeAndEqualsShouldWorkOnDifferentClasses() throws Exception {
QualifierDefinition directQualifier1 = QualifierDefinition
.forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier"));
QualifierDefinition directQualifier2 = QualifierDefinition
.forElement(ReflectionUtils.findField(ConfigB.class, "directQualifier"));
QualifierDefinition differentDirectQualifier1 = QualifierDefinition.forElement(
ReflectionUtils.findField(ConfigA.class, "differentDirectQualifier"));
QualifierDefinition differentDirectQualifier2 = QualifierDefinition.forElement(
ReflectionUtils.findField(ConfigB.class, "differentDirectQualifier"));
QualifierDefinition customQualifier1 = QualifierDefinition
.forElement(ReflectionUtils.findField(ConfigA.class, "customQualifier"));
QualifierDefinition customQualifier2 = QualifierDefinition
.forElement(ReflectionUtils.findField(ConfigB.class, "customQualifier"));
assertThat(directQualifier1.hashCode()).isEqualTo(directQualifier2.hashCode());
assertThat(differentDirectQualifier1.hashCode())
.isEqualTo(differentDirectQualifier2.hashCode());
assertThat(customQualifier1.hashCode()).isEqualTo(customQualifier2.hashCode());
assertThat(differentDirectQualifier1).isEqualTo(differentDirectQualifier1)
.isEqualTo(differentDirectQualifier2).isNotEqualTo(directQualifier2);
assertThat(directQualifier1).isEqualTo(directQualifier1)
.isEqualTo(directQualifier2).isNotEqualTo(differentDirectQualifier1);
assertThat(customQualifier1).isEqualTo(customQualifier1)
.isEqualTo(customQualifier2).isNotEqualTo(differentDirectQualifier1);
}
@Configuration
static class ConfigA {
@MockBean
private Object noQualifier;
@MockBean
@Qualifier("test")
private Object directQualifier;
@MockBean
@Qualifier("different")
private Object differentDirectQualifier;
@MockBean
@CustomQualifier
private Object customQualifier;
}
static class ConfigB {
@MockBean
@Qualifier("test")
private Object directQualifier;
@MockBean
@Qualifier("different")
private Object differentDirectQualifier;
@MockBean
@CustomQualifier
private Object customQualifier;
}
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomQualifier {
}
}

View File

@@ -0,0 +1,126 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link ResetMocksTestExecutionListener}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ResetMocksTestExecutionListenerTests {
@Autowired
private ApplicationContext context;
@Test
public void test001() {
given(getMock("none").greeting()).willReturn("none");
given(getMock("before").greeting()).willReturn("before");
given(getMock("after").greeting()).willReturn("after");
}
@Test
public void test002() {
assertThat(getMock("none").greeting()).isEqualTo("none");
assertThat(getMock("before").greeting()).isNull();
assertThat(getMock("after").greeting()).isNull();
}
public ExampleService getMock(String name) {
return this.context.getBean(name, ExampleService.class);
}
@Configuration
static class Config {
@Bean
public ExampleService before(MockitoBeans mockedBeans) {
ExampleService mock = mock(ExampleService.class, MockReset.before());
mockedBeans.add(mock);
return mock;
}
@Bean
public ExampleService after(MockitoBeans mockedBeans) {
ExampleService mock = mock(ExampleService.class, MockReset.after());
mockedBeans.add(mock);
return mock;
}
@Bean
public ExampleService none(MockitoBeans mockedBeans) {
ExampleService mock = mock(ExampleService.class);
mockedBeans.add(mock);
return mock;
}
@Bean
@Lazy
public ExampleService fail() {
// gh-5870
throw new RuntimeException();
}
@Bean
public BrokenFactoryBean brokenFactoryBean() {
// gh-7270
return new BrokenFactoryBean();
}
}
static class BrokenFactoryBean implements FactoryBean<String> {
@Override
public String getObject() throws Exception {
throw new IllegalStateException();
}
@Override
public Class<?> getObjectType() {
return String.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright 2012-2016 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
*
* http://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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.boot.test.mock.mockito.example.SimpleExampleService;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
/**
* Test {@link SpyBean} on a configuration class can be used to spy existing beans.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
public class SpyBeanOnConfigurationClassForExistingBeanIntegrationTests {
@Autowired
private ExampleServiceCaller caller;
@Test
public void testSpying() throws Exception {
assertThat(this.caller.sayGreeting()).isEqualTo("I say simple");
verify(this.caller.getService()).greeting();
}
@Configuration
@SpyBean(SimpleExampleService.class)
@Import({ ExampleServiceCaller.class, SimpleExampleService.class })
static class Config {
}
}

Some files were not shown because too many files have changed in this diff Show More