Testing MVC Controller Methods with REST Endpoints in JUnit

Our NixMash Microservices app currently has a UserService REST Service, a Web Client, and NixMash Jangles as a shared library for POJOs and such.

In this post we're going to look at how to test a Web UserController method that retrieves a list of Users from the UserService. The UserService is independent of the Web JUnit tests. It's down, in other words, so how are we going to test the method when we know it's going to fail?

The UserController GetUsers Method

For the path of /users we have a getUsers() method in our UserController which retrieves a JSON list of Users from our REST UserService. The design of our REST interactions from the Web Client to the User Service as demonstrated below is to wrap the REST calls in a try/catch and return a custom RestProcessingException if there's a problem.

We retrieve the User list with userClientService.getRestUsers() and if all goes well return the populated users.html Mustache template. If an exception occurs we display an error page with the exception message.

Testing the RestProcessingException

We're going to test the method in its raw state, knowing that UserService will not be responding.

Stubbing the Controller Method with Mockito

Now we move to the interesting part, where we want to test the method and simulate how it would perform if UserService was functioning properly.

First we'll mock with UserController Class in our @Before method and give it the behavior that when called it will return a Mockito Answer we provide.

The Mockito Answer

A Mockito Answer is replacing a method with another method for testing, or stubbing the original method with our answer. In our answer() method we're simulating the behavior of the original method by adding a list of Users to our Mustache model, then populating the Template as we do in the UserController method.

The Test

Now we can test the method. Our Mustache users.html template in our Test Resources area is processed with the appropriate title.

Source Code Notes for this Post

Source code discussed in this post is found in NixMash Microservices on GitHub. Code for this particular post is found in branch microservices-v0.1.0 - Initial Layout and Structure.

Posted July 21, 2017 10:27 AM EDT

More Like This Post