Friday, March 28, 2014

Set a private field on a class you need to Unit Test

Well, of course, you could make your field with default access, or you can add some boilerplate setter, or you could fancy whipping up a utility using reflection, but spring-test has already thought of that.

Let's say you want to test your DonkeyController:

This is how you can easily set the private field donkeyDAO, without changes in the class under test:

ReflectionTestUtils is in spring-test:

Cheers!

Saturday, January 25, 2014

Spring MVC Json Rest Service Authentication Example

Just a quick example of using simple username/password authentication for a Spring RestTemplate Client-> Spring MVC Rest JSON service.

The idea is:
  1. Client fires a http request using Spring's RestTemplate
  2. The request is intercepted on the client side by Spring's ClientHttpRequestInterceptor
  3. The interceptor adds authentication headers to the http request before passing it on to the server
  4. The server side has a javax.servlet.Filter which looks at the request headers
  5. If the filter finds the headers injected by the client's interceptor and the header's values are correct (username/password correct) - the filter passes the request onto the server side logic for regular processing (chain.doFilter)
  6. If the Filter does not find the http headers or they have incorrect values, the filter writes "Unauthorized" to the http response.
I run it in tomcat through eclipse. To fire the requests through the client,  I just run the client(com.app.client.RestDonkeyClient)  within the same project by right-clinking on it and 'Run As -> Java Application. Both, service and client are in the same project for convenience.

https://github.com/boyko11/spring-rest-authenticate

References:
http://www.jeenisoftware.com/spring-3-mvc-json-example/
http://svenfila.wordpress.com/2012/01/05/resttemplate-with-custom-http-headers/