Add @MockBean support

Add a `@MockBean` annotation which can be used to setup and inject mocks
into an application context. The annotation can be used on test classes,
test fields, configuration classes or configuration fields. When used on
a field the annotation also acts as an injection point.

Fixes gh-5042
This commit is contained in:
Phillip Webb
2016-02-22 12:04:58 -08:00
parent 0829a1bde8
commit 45c4f5f3f1
37 changed files with 2818 additions and 1 deletions

View File

@@ -0,0 +1,91 @@
/*
* 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.Answers;
import org.mockito.internal.util.MockUtil;
import org.mockito.mock.MockCreationSettings;
import org.springframework.boot.test.mock.mockito.example.ExampleExtraInterface;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link MockDefinition}.
*
* @author Phillip Webb
*/
public class MockDefinitionTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void ClassToMockMustNotBeNull() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ClassToMock must not be null");
new MockDefinition(null, null, null, null, false, null);
}
@Test
public void createWithDefaults() throws Exception {
MockDefinition definition = new MockDefinition(null, ExampleService.class, null,
null, false, null);
assertThat(definition.getName()).isNull();
assertThat(definition.getClassToMock()).isEqualTo(ExampleService.class);
assertThat(definition.getExtraInterfaces()).isEmpty();
assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_DEFAULTS);
assertThat(definition.isSerializable()).isFalse();
assertThat(definition.getReset()).isEqualTo(MockReset.AFTER);
}
@Test
public void createExplicit() throws Exception {
MockDefinition definition = new MockDefinition("name", ExampleService.class,
new Class<?>[] { ExampleExtraInterface.class },
Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE);
assertThat(definition.getName()).isEqualTo("name");
assertThat(definition.getClassToMock()).isEqualTo(ExampleService.class);
assertThat(definition.getExtraInterfaces())
.containsExactly(ExampleExtraInterface.class);
assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS);
assertThat(definition.isSerializable()).isTrue();
assertThat(definition.getReset()).isEqualTo(MockReset.BEFORE);
}
@Test
public void createMock() throws Exception {
MockDefinition definition = new MockDefinition("name", ExampleService.class,
new Class<?>[] { ExampleExtraInterface.class },
Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE);
ExampleService mock = definition.createMock();
MockCreationSettings<?> settings = new MockUtil().getMockSettings(mock);
assertThat(mock).isInstanceOf(ExampleService.class);
assertThat(mock).isInstanceOf(ExampleExtraInterface.class);
assertThat(settings.getMockName().toString()).isEqualTo("name");
assertThat(settings.getDefaultAnswer())
.isEqualTo(Answers.RETURNS_SMART_NULLS.get());
assertThat(settings.isSerializable()).isTrue();
assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE);
}
}

View File

@@ -0,0 +1,184 @@
/*
* 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.ArrayList;
import java.util.List;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Answers;
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.MyMockBean;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link MockDefinitionsParser}.
*
* @author Phillip Webb
*/
public class MockDefinitionsParserTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private MockDefinitionsParser parser = new MockDefinitionsParser();
@Test
public void parseSingleMockBean() {
this.parser.parse(SingleMockBean.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getDefinition(0).getClassToMock()).isEqualTo(ExampleService.class);
}
@Test
public void parseRepeatMockBean() {
this.parser.parse(RepeatMockBean.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getDefinition(0).getClassToMock()).isEqualTo(ExampleService.class);
assertThat(getDefinition(1).getClassToMock())
.isEqualTo(ExampleServiceCaller.class);
}
@Test
@Ignore // See SPR-13973
public void parseMetaMockBean() {
this.parser.parse(MetaMockBean.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getDefinition(0).getClassToMock()).isEqualTo(ExampleService.class);
}
@Test
public void parseMockBeanAttributes() throws Exception {
this.parser.parse(MockBeanAttributes.class);
assertThat(getDefinitions()).hasSize(1);
MockDefinition definition = getDefinition(0);
assertThat(definition.getName()).isEqualTo("Name");
assertThat(definition.getClassToMock()).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);
}
@Test
public void parseOnClassAndField() throws Exception {
this.parser.parse(OnClassAndField.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getDefinition(0).getClassToMock()).isEqualTo(ExampleService.class);
assertThat(getDefinition(1).getClassToMock())
.isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseInferClassToMock() throws Exception {
this.parser.parse(InferClassToMock.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getDefinition(0).getClassToMock()).isEqualTo(ExampleService.class);
}
@Test
public void parseMissingClassToMock() throws Exception {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Unable to deduce class to mock");
this.parser.parse(MissingClassToMock.class);
}
@Test
public void parseMultipleClasses() throws Exception {
this.parser.parse(MultipleClasses.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getDefinition(0).getClassToMock()).isEqualTo(ExampleService.class);
assertThat(getDefinition(1).getClassToMock())
.isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseMultipleClassesWithName() 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(MultipleClassesWithName.class);
}
private MockDefinition getDefinition(int index) {
return getDefinitions().get(index);
}
private List<MockDefinition> getDefinitions() {
return new ArrayList<MockDefinition>(this.parser.getDefinitions());
}
@MockBean(ExampleService.class)
static class SingleMockBean {
}
@MockBeans({ @MockBean(ExampleService.class), @MockBean(ExampleServiceCaller.class) })
static class RepeatMockBean {
}
@MyMockBean(ExampleService.class)
static class MetaMockBean {
}
@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 OnClassAndField {
@MockBean(ExampleServiceCaller.class)
private Object caller;
}
@MockBean({ ExampleService.class, ExampleServiceCaller.class })
static class MultipleClasses {
}
@MockBean(name = "name", classes = { ExampleService.class,
ExampleServiceCaller.class })
static class MultipleClassesWithName {
}
static class InferClassToMock {
@MockBean
private ExampleService exampleService;
}
@MockBean
static class MissingClassToMock {
}
}

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,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.mock.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.context.ContextCustomizer;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link MockitoContextCustomizerFactory}.
*
* @author Phillip Webb
*/
@RunWith(MockitoJUnitRunner.class)
public class MockitoContextCustomizerFactoryTests {
private final MockitoContextCustomizerFactory factory = new MockitoContextCustomizerFactory();
@Test
public void getContextCustomizerWithoutAnnotationReturnsCustomizer()
throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(NoRegisterMocksAnnotation.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void getContextCustomizerWithAnnotationReturnsCustomizer() throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(WithRegisterMocksAnnotation.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void getContextCustomizerUsesMocksAsCacheKey() throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(WithRegisterMocksAnnotation.class, null);
assertThat(customizer).isNotNull();
ContextCustomizer same = this.factory
.createContextCustomizer(WithSameRegisterMocksAnnotation.class, null);
assertThat(customizer).isNotNull();
ContextCustomizer different = this.factory.createContextCustomizer(
WithDifferentRegisterMocksAnnotation.class, null);
assertThat(customizer).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 NoRegisterMocksAnnotation {
}
@MockBean({ Service1.class, Service2.class })
static class WithRegisterMocksAnnotation {
}
@MockBean({ Service2.class, Service1.class })
static class WithSameRegisterMocksAnnotation {
}
@MockBean({ Service1.class })
static class WithDifferentRegisterMocksAnnotation {
}
interface Service1 {
}
interface Service2 {
}
}

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.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 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 = new MockDefinition(ExampleService.class);
MockDefinition d2 = new MockDefinition(ExampleServiceCaller.class);
MockitoContextCustomizer c1 = new MockitoContextCustomizer(NO_DEFINITIONS);
MockitoContextCustomizer c2 = new MockitoContextCustomizer(
new LinkedHashSet<MockDefinition>(Arrays.asList(d1, d2)));
MockitoContextCustomizer c3 = new MockitoContextCustomizer(
new LinkedHashSet<MockDefinition>(Arrays.asList(d2, d1)));
assertThat(c2.hashCode()).isEqualTo(c3.hashCode());
assertThat(c1).isEqualTo(c1).isNotEqualTo(c2);
assertThat(c2).isEqualTo(c2).isEqualTo(c3).isNotEqualTo(c1);
}
}

View File

@@ -0,0 +1,107 @@
/*
* 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.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.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link MockitoInitializeTestExecutionListener}.
*
* @author Phillip Webb
*/
public class MockitoInitializeTestExecutionListenerTests {
private MockitoInitializeTestExecutionListener listener = new MockitoInitializeTestExecutionListener();
@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 prepareTestInstanceShouldInitMockitoAnnotation() throws Exception {
WithMockitoAnnotation instance = new WithMockitoAnnotation();
this.listener.prepareTestInstance(mockTestContext(instance));
assertThat(instance.mock).isNotNull();
assertThat(instance.captor).isNotNull();
}
@Test
public void prepareTestInstanceShouldInjectMockBeans() throws Exception {
WithMockBeans instance = new WithMockBeans();
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 WithMockitoAnnotation {
@Mock
InputStream mock;
@Captor
ArgumentCaptor<InputStream> captor;
}
static class WithMockBeans {
@MockBean
InputStream mockBean;
}
}

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.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
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;
/**
* Test for {@link MockitoPostProcessor}. See also the integration tests in the
* {@code runner} package.
*
* @author Phillip Webb
*/
public class MockitoPostProcessorTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void cannotMockMulipleBeans() {
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 existing bean to replace "
+ "but found [example1, example2]");
context.refresh();
}
@Configuration
@MockBean(ExampleService.class)
static class MultipleBeans {
@Bean
public ExampleService example1() {
return new FailingExampleService();
}
@Bean
public ExampleService example2() {
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 configuration class can be used to replace existing beans.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
public class OnConfigurationClassForExistingBeanIntegrationTests {
@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 OnConfigurationClassForNewBeanIntegrationTests {
@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 OnConfigurationFieldForExistingBeanIntegrationTests {
@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 OnConfigurationFieldForNewBeanIntegrationTests {
@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.OnContextHierarchyIntegrationTests.ChildConfig;
import org.springframework.boot.test.mock.mockito.OnContextHierarchyIntegrationTests.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 OnContextHierarchyIntegrationTests {
@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,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 OnTestClassForExistingBeanIntegrationTests {
@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 OnTestClassForNewBeanIntegrationTests {
@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 OnTestFieldForExistingBeanCacheIntegrationTests} so one of them should trigger
* application context caching.
*
* @author Phillip Webb
* @see OnTestFieldForExistingBeanIntegrationTests
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = OnTestFieldForExistingBeanConfig.class)
public class OnTestFieldForExistingBeanCacheIntegrationTests {
@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,34 @@
/*
* 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.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Config for {@link OnTestFieldForExistingBeanIntegrationTests} and
* {@link OnTestFieldForExistingBeanCacheIntegrationTests}. Extracted to a shared config
* to trigger caching.
*
* @author Phillip Webb
*/
@Configuration
@Import(ExampleServiceCaller.class)
public class OnTestFieldForExistingBeanConfig {
}

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 OnTestFieldForExistingBeanCacheIntegrationTests
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = OnTestFieldForExistingBeanConfig.class)
public class OnTestFieldForExistingBeanIntegrationTests {
@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,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.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 field can be used to inject new mock instances.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
public class OnTestFieldForNewBeanIntegrationTests {
@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, FailingExampleService.class })
static class Config {
}
}

View File

@@ -0,0 +1,88 @@
/*
* 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.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.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
*/
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ResetMocksTestExecutionListenerTests {
static boolean test001executed;
@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");
test001executed = true;
}
@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() {
return mock(ExampleService.class, MockReset.before());
}
@Bean
public ExampleService after() {
return mock(ExampleService.class, MockReset.before());
}
@Bean
public ExampleService none() {
return mock(ExampleService.class);
}
}
}

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.mock.mockito.example;
/**
* Example extra interface for mocking tests.
*
* @author Phillip Webb
*/
public interface ExampleExtraInterface {
String doExtra();
}

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.mock.mockito.example;
/**
* Example service interface for mocking tests.
*
* @author Phillip Webb
*/
public interface ExampleService {
String greeting();
}

View File

@@ -0,0 +1,42 @@
/*
* 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.example;
import java.security.Provider.Service;
/**
* Example bean for mocking tests that calls {@link Service}.
*
* @author Phillip Webb
*/
public class ExampleServiceCaller {
private final ExampleService service;
public ExampleServiceCaller(ExampleService service) {
this.service = service;
}
public ExampleService getService() {
return this.service;
}
public String sayGreeting() {
return "I say " + this.service.greeting();
}
}

View File

@@ -0,0 +1,34 @@
/*
* 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.example;
import org.springframework.stereotype.Service;
/**
* An {@link ExampleService} that always throws an exception.
*
* @author Phillip Webb
*/
@Service
public class FailingExampleService implements ExampleService {
@Override
public String greeting() {
throw new IllegalStateException("Failed");
}
}

View File

@@ -0,0 +1,37 @@
/*
* 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.example;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.core.annotation.AliasFor;
@Target({ ElementType.TYPE, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@MockBean
public @interface MyMockBean {
@AliasFor(annotation = MockBean.class, attribute = "value")
Class<?> value();
}