Here's a fun example of using @MockBeans in Spring Boot. We're testing conditional Google Analytics Tracking Script page display. We want the tracking script to display for all Anonymous and Registered Users BUT NOT for anyone in ROLE_POSTS or ROLE_ADMIN. A pretty common scenario.
The setting determining if Google Analytics Tracking Script is to display on site pages is in a Global property stored in a SiteOptions Component. You'll find more about that in this NixMash Post.
We're going to mock the SiteOptions component so we can set the addGoogleAnalytics property.
We'll configure our @MockBean in setup() where we tell it to return TRUE and generate a specific Tracking ID. In Development we obviously are not enabling Analytics Tracking, so mocking the SiteOptions component gives us the ability to change its settings as needed.
Here is one of our tests using our Mock siteOptions Bean where addGoogleAnalytics=true confirming the page DOES NOT contain a Google Tracking ID value for Admin.
Besides checking the response content, we're going to test the GlobalController method that determines the script display directly. Here we pass our @MockBean in our test GlobalController constructor.
We test again, this time calling the controller method directly.
Source code discussed in this post can be found in my NixMash Blog project located on GitHub.