Testing a Spring Cloud Service Endpoint with @MockBean

In our NixMash Spring Cloud Application's MVC Client we're retrieving Posts from our Spring Cloud Post Service to display on our Home Page. The "Recent Posts and Links" shown at bottom are posts that are retrieved from the Post Service's default REST Endpoint.

The issue then is how do we test the Home Page with a mockMvc(get("/")) like any ordinary MVC page, but with the Cloud Service not running?

First a look at how we're retrieving those posts, which is using a Spring @FeignClient Reader to our post-service REST Endpoint.

We use the reader in our MVC Client Controller to retrieve the posts.

The Tests: @MockBean in Play

Now to the crux of the matter, testing the MVC Home Page independent of the Posts Service. Nothing unusual about the @Test itself other confirming that the posts from our [nonexistent] Posts Service are present and accounted for.

We're going to mock our Posts REST Endpoint by mocking our PostReader Bean. Then we use that @MockBean when configuring our mockMvc environment. Finally we set a when() condition on our @MockBean Reader Method to return an empty Resource List of Posts. And with that, our mockMvc(get("/")) test will pass.


As a bonus, the test code also shows how to initialize a Spring Hateoas Resources object. Or for some Google Juice…

How To Initialize a Spring Hateoas Resource; How To Initialize a Spring Resource

There, that oughta do it.

Source Code Notes for this Post

Source code discussed in our Spring Cloud Series is found in NixMash Spring Cloud on GitHub. Code for this particular post is found in branch nixmashcloud-v0.1.0 – Initial Layout and Structure.