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?
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.
We're going to test the method in its raw state, knowing that UserService will not be responding.
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.
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.
Now we can test the method. Our Mustache users.html template in our Test Resources area is processed with the appropriate title.
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.