It's August 2016 and the Spring Boot team recently released Spring Boot 1.4 ( on July 28th, 2016 ). Some of the biggest improvements and simplifications are around unit and integration testing. We'll take a focused look at two of the newly added features:
New Dependencies and a New Class Runner
- two new dependencies were added called
spring-boot-test-autoconfigure. If you're already using the
spring-boot-starter-test"starter-dependency", both will automatically be included.
- Spring Boot 1.4 builds on the also recently released, Spring Framework 4.3. A small but welcome improvement from the Spring Framework: you can replace
SpringRunnerclass is simply a shortened alias.
The newly introduced annotation, (
@MockBean), adds generalized support for mocking of any Spring bean. If you've used Mockito Annotations before,
@MockBean is simliar to
@Mock but with Spring support.
Suppose we have a simple
@Component-annoated class called
DailyWeather and a simple
@Service-annotated class called
WeatherService. Additionally, the
DailyWeatherclass relies on the
WeatherService as a dependency and is injected via the constructor.
To unit test the
DailyWeather component, you can mock the
WeatherService dependency by simply annotating it with
@MockBean and then use
Mockito.when(..) like normal.
You're probably thinking, that's neat, but that's not really different than using Mockito Annotations. And you're right, it's not. But it gets better though.
Not only will
@MockBean provide you with a mock, it will also add that mock as a bean (as the name suggests) within the ApplicationContext, and override any existing beans either by name or by type
You can use it in several different places.
At the Test Class Level
At the Configuration Class Level
At the Configuration Field Level
Another new annotation introduced,
@SpyBean can be used in tests to create spys. A spy wraps an existing bean and "spies on it", allowing it to verify method invocations and provide mocking of individual methods without affecting any of the other methods within the class. You can think of a Spy as a "partial mock".
You can use it in all of the same places as