MockBean
Deprecated (for removal)
Annotation that can be used to add mocks to a Spring 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. When registered by type, any existing single bean of a matching type (including subclasses) in the context will be replaced by the mock. When registered by name, an existing bean can be specifically targeted for replacement by a mock. In either case, 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 {
}
}
@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.
Author
Phillip Webb
Since
1.4.0
Deprecated
since 3.4.0 for removal in 3.6.0 in favor of org.springframework.test.context.bean.override.mockito.MockitoBean