@Target(value={TYPE,FIELD}) @Retention(value=RUNTIME) @Documented @Repeatable(value=MockBeans.class) public @interface MockBean
ApplicationContext
. Can be
used as a class level annotation or on fields in either @Configuration
classes,
or test classes that are @RunWith
the SpringRunner
.
Mocks can be registered by type or by bean name
. Any existing single
bean of the same type defined in the context will be replaced by the mock. If no
existing bean is defined a new one will be added. Dependencies that are known to the
application context but are not beans (such as those
registered directly
) will not be found and a mocked bean will be added to the context
alongside the existing dependency.
When @MockBean
is used on a field, as well as being registered in the
application context, the mock will also be injected into the field. Typical usage might
be:
@RunWith(SpringRunner.class) public class ExampleTests { @MockBean private ExampleService service; @Autowired private UserOfService userOfService; @Test public void testUserOfService() { given(this.service.greet()).willReturn("Hello"); String actual = this.userOfService.makeUse(); assertEquals("Was: Hello", actual); } @Configuration @Import(UserOfService.class) // A @Component injected with ExampleService static class Config { } }If there is more than one bean of the requested type, qualifier metadata must be specified at field level:
@RunWith(SpringRunner.class) public class ExampleTests { @MockBean @Qualifier("example") private ExampleService service; ... }
This annotation is @Repeatable
and may be specified multiple times when working
with Java 8 or contained within an @MockBeans
annotation.
MockitoPostProcessor
Modifier and Type | Optional Element and Description |
---|---|
org.mockito.Answers |
answer
The
Answers type to use on the mock. |
Class<?>[] |
classes
The classes to mock.
|
Class<?>[] |
extraInterfaces
Any extra interfaces that should also be declared on the mock.
|
String |
name
The name of the bean to register or replace.
|
MockReset |
reset
The reset mode to apply to the mock bean.
|
boolean |
serializable
If the generated mock is serializable.
|
Class<?>[] |
value
The classes to mock.
|
public abstract String name
@AliasFor(value="value") public abstract Class<?>[] classes
When @MockBean
also defines a name
this attribute can only contain
a single value.
If this is the only specified attribute consider using the value
alias
instead.
public abstract Class<?>[] extraInterfaces
MockSettings.extraInterfaces(Class...)
for details.public abstract org.mockito.Answers answer
Answers
type to use on the mock.public abstract boolean serializable
MockSettings.serializable()
for
details.public abstract MockReset reset
MockReset.AFTER
meaning that mocks are automatically reset after each test method is invoked.Copyright © 2021 Pivotal Software, Inc.. All rights reserved.