I have few working code to set up MockMVc in different ways with the new Spring Boot 1.4 #WebMvcTest. I understand the standaloneSetup approach. What I want to know is the difference between setting up MockMvc through WebApplicationContext and by autowiring MockMvc.
Code Snippet 1: MockMvc through WebApplicationContext Setup
#RunWith(SpringRunner.class)
#WebMvcTest(controllers = ProductController.class)
public class ProductControllerTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
#MockBean
private ProductService productServiceMock;
#Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
#Test
public void testShowProduct() throws Exception {
Product product1 = new Product();
/*Code to initialize product1*/
when(productServiceMock.getProductById(1)).thenReturn(product1);
MvcResult result = mockMvc.perform(get("/product/{id}/", 1))
.andExpect(status().isOk())
/*Other expectations*/
.andReturn();
}
}
As per WebMvcTest API documentation, By default, tests annotated with #WebMvcTest will also auto-configure Spring Security and MockMvc. So, I expected a 401 Unauthorized status code here, but the test passes with a 200 status code.
Next, I tried auto wiring MockMvc, but the test fails with 401 Unauthorized status code, unless I add #AutoConfigureMockMvc(secure=false) or update the #WebMvcTest annotation to disable security:
#WebMvcTest(controllers = IndexController.class, secure = false)
Following is the code that passes ONLY AFTER explicitly disabling security.
Code Snippet 2: MockMvc through Autowiring
#RunWith(SpringRunner.class)
#WebMvcTest(controllers = ProductController.class)
#AutoConfigureMockMvc(secure=false)
public class ProductControllerTest {
#Autowired
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
#MockBean
private ProductService productServiceMock;
#Test
public void testShowProduct() throws Exception {
Product product1 = new Product();
/*Code to initialize product1*/
when(productServiceMock.getProductById(1)).thenReturn(product1);
MvcResult result = mockMvc.perform(get("/product/{id}/", 1))
.andExpect(status().isOk())
/*Other expectations*/
.andReturn();
}
}
So my questions are:
Why didn't Code snippet 1 report a a 401 Unauthorized status code error while auto wiring MockMvc did. Also reiterating what the official doc says By default, tests annotated with #WebMvcTest will also auto-configure Spring Security and MockMvc. But, in this case it appears #WebMvcTest has nothing to do with auto-configuring Spring Security (Because Code Snippet 1 passes without any 401 error). It finally boils down to how I set up the MockMvc. Am I correct here?
What are the differences/objectives between/of both the approaches?
How does disabling security via #AutoConfigureMockMvc(secure=false) differs from doing through #WebMvcTest(controllers = IndexController.class, secure = false). Which one is the preferred approached or when (or where) to use them?
I also come across similar problem. #WebMvcTest auto configures Spring Security with basic auth but I have a WebSecurityConfig class that extends WebSecurityConfigurerAdapter. In this class I disabled basic auth and configured token base security. That means WebSecurityConfig class is not used to configure Spring Security.
To resolve the problem, I added #ContextConfiguration to my unit test class and added mocks of dependencies of WebSecurityConfig class.
#RunWith(SpringRunner.class)
#WebMvcTest(controllers = CategoryRestService.class)
#ContextConfiguration(classes = {MjApplication.class, WebSecurityConfig.class})
public class CategoryRestServiceTest {
#MockBean
private CategoryRepository repository;
#MockBean
CurrentUserDetailsService currentUserDetailsService;
#MockBean
TokenAuthProvider tokenAuthProvider;
#Autowired
MockMvc mockMvc;
private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
#Test
public void getCategories() throws Exception {
Category category1 = new Category();
category1.setName("Test Category 1");
category1.setId(1L);
Category category2 = new Category();
category2.setName("Test Category 2");
category2.setId(2L);
List<Category> categoryList = new ArrayList<Category>();
categoryList.add(category1);
categoryList.add(category2);
given(this.repository.findAll())
.willReturn(categoryList);
mockMvc.perform(get("/public/rest/category"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$[0].name", is("Test Category 1")))
.andExpect(jsonPath("$[1].id", is(2)))
.andExpect(jsonPath("$[1].name", is("Test Category 2")));
}
}
According to this issue in github
https://github.com/spring-projects/spring-boot/issues/5476
#WebMvcTest auto configures by default, a basic auth when spring-security-test is in the class path
Answering your questions:
In the code snippet 1, you not injected the MockMvc in your test class, you should add .apply(springSecurity()) in the builder on the setup method, so spring would use the basic configuration (not your custom security configuration if you have one)
both approaches does basically the same thing, the difference is that the second comes with the basic auth already in the MockMvc, that is why you have to use the secure=false
From the documentation:
By default, tests annotated with #WebMvcTest will also auto-configure
Spring Security and MockMvc (include support for HtmlUnit WebClient
and Selenium WebDriver). For more fine-grained control of MockMVC the
#AutoConfigureMockMvc annotation can be used.
I'm not sure this is directly related, but there is an outstanding bug where, if using spring boot and #WebMvcTest, your custom #EnableWebSecurity config class will be ignored. A couple workarounds are mentioned in the bug report. I'm using:
#WebMvcTest(includeFilters = #Filter(classes = EnableWebSecurity.class))
I don't know if this is correct way or not but I could disable configurations class by using like below
#WebMvcTest(ProductController.class)
#ContextConfiguration(classes = ProductController.class)
public class ProductControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private ProductService productServiceMock;
Related
I'm trying to test a spring rest controller class using JUnit, Mockito, Spring test and Spring Security test. The following is my rest controller class for which i'm performing the test;
#RestController
public class EmployeeRestController {
#Autowired
private EmployeeService employeeService;
#PreAuthorize("hasAnyRole('ROLE_EMPSUPEADM')")
#RequestMapping(value = "/fetch-timezones", method = RequestMethod.GET)
public ResponseEntity<List<ResponseModel>> fetchTimeZones() {
List<ResponseModel> timezones = employeeService.fetchTimeZones();
return new ResponseEntity<>(timezones, HttpStatus.OK);
}
}
The following is my test class;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {SpringConfiguration.class})
#WebAppConfiguration
public class EmployeeRestControllerUnitTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
#Mock
private EmployeeService employeeService;
#InjectMocks
private EmployeeRestController employeeRestController;
#Before
public void init() {
MockitoAnnotations.initMocks(this);
Mockito.reset(employeeService);
mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.build();
}
#Test
#WithMockUser(roles = {"EMPSUPEADM"})
public void testFetchTimezones() {
try {
mockMvc.perform(get("/fetch-timezones"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", hasSize(4)));
verify(emploeeService, times(1)).fetchTimeZones();
verifyNoMoreInteractions(employeeService);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I made the above test class by refering many tutorials. The problem is i'm not able to understand everything clearly. so, i'm having the following doubts.
I'm creating a mock of EmployeeService and injecting it into EmployeeRestController using #InjectMocks, then why i'm getting the following failure;
Wanted but not invoked:
careGroupService.fetchTimeZones();
-> at com.example.api.test
.restcontroller.EmployeeRestControllerUnitTest
.testFetchTimezones(EmployeeRestControllerUnitTest.java:73)
Actually, there were zero interactions with this mock.
How does MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); works exactly.
I know that MockMvcBuilders.standaloneSetup(employeeRestController) is for testing individual controller classes and spring configuration will not be available for this method. How can we provide spring configuraton for this method, is it possible.
Finally, how does this piece of code: Mockito.reset(employeeService); works.
1) you do verify for
verify(emploeeService, times(1)).fetchTimeZones();
but you didn't setup mock behaviour for it (before you call mockMvc.perform(get("/fetch-timezones"))).
List<ResponseModel> timezones = new ArrayList<>();
when(emploeeService.fetchTimeZones()).thenReturn(timezones );
2) create MockMvc from context. mockmvc emulates web container, use mock for all where is possible but supports http call and gave the possibility to call controller.
It stands up the Dispatcher Servlet and all required MVC components,
allowing us to test an endpoint in a proper web environment, but
without the overhead of running a server.
3) when you use:
#MockBean private EmployeeService employeeService;
you override real service. remove it from test class real service will be used in testing. Instead of use #Mock use #MockBean. #MockBean it's override by container, with #Mock you need to inject this into controller by reflection
or without spring boot with reflection:
#Before
public void init() {
MockitoAnnotations.initMocks(this);
Mockito.reset(employeeService);
mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.build();
EmployeeRestController employeeRestController=
webAppContext.getBean(EmployeeRestController.class);
ReflectionTestUtils.setField(employeeRestController,
"employeeService",
employeeService);
}
4) Mockito.reset(employeeService);- you reset all behaviors that you setupped before. Mock contains information from when(), verify() and controls it , call reset - it's clean all information.
I'd like to test a Spring Boot Rest controller, which is secured using Spring security, and use mocks inside it. I have tried with Mockito, but I think any mocking tool should do the trick.
To enable Spring security in my tests, I first did as follow:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Main.class)
#TestPropertySource(value="classpath:application-test.properties")
#WebAppConfiguration
#ContextConfiguration
public class MyTest{
protected MockMvc mockMvc;
#Autowired
private WebApplicationContext wac;
#Before
public void setUp(){
mockMvc = MockMvcBuilders
.webAppContextSetup(wac)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
}
#Test
public void doTheTest(){
mockMvc.perform(post("/user/register")
.with(SecurityMockMvcRequestPostProcessors.csrf())
.content(someContent()));
}
}
Until there, it works well.
After this step, I wished to add mocks to test my secured controller in isolation.
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Main.class)
#TestPropertySource(value="classpath:application-test.properties")
#WebAppConfiguration
#ContextConfiguration
public class MyTest{
protected MockMvc mockMvc;
#Mock
private Myservice serviceInjectedInController;
#InjectMocks
private MyController myController;
#Autowired
private WebApplicationContext wac;
#Before
public void setUp(){
mockMvc = MockMvcBuilders
.webAppContextSetup(wac)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
}
#Test
public void doTheTest(){
mockMvc.perform(post("/user/register")
.with(SecurityMockMvcRequestPostProcessors.csrf())
.content(someContent()));
}
}
Unfortunately, the mocked service is not injected in the controller, as there is nothing relating the MockMVC and the Mocks, so the mocks are not injected in the controller.
So I tried changing the configuration of the MockMVC, as follows:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Main.class)
#TestPropertySource(value="classpath:application-test.properties")
#WebAppConfiguration
#ContextConfiguration
public class MyTest{
protected MockMvc mockMvc;
#Mock
private Myservice serviceInjectedInController;
#InjectMocks
private MyController myController;
#Before
public void setUp(){
mockMvc = MockMvcBuilders
.standAloneSetup(myController)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
}
#Test
public void doTheTest(){
mockMvc.perform(post("/user/register")
.with(SecurityMockMvcRequestPostProcessors.csrf())
.content(someContent()));
}
}
But in this case, I have another issue. Spring security is complaining about the configuration:
java.lang.IllegalStateException: springSecurityFilterChain cannot be null. Ensure a Bean with the name springSecurityFilterChain implementing Filter is present or inject the Filter to be used.
I have no other idea to make security and mocking. Any idea? Or should I do another way?
Thanks.
By default the integration looks for a bean with the name of "springSecurityFilterChain". In the example that was provided, a standalone setup is being used which means MockMvc will not be aware of the WebApplicationContext provided within the test and thus not be able to look up the "springSecurityFilterChain" bean.
The easiest way to resolve this is to use something like this:
MockMvc mockMvc = MockMvcBuilders
// replace standaloneSetup with line below
.webAppContextSetup(wac)
.alwaysDo(print())
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
If you really want to use a standaloneSetup (doesn't really make sense since you already have a WebApplicationContext), you can explicitly provide the springSecurityFilterChain using:
#Autowired
FilterChainProxy springSecurityFilterChain;
#Before
public void startMocks(){
controller = wac.getBean(RecipesController.class);
MockMvc mockMvc = MockMvcBuilders
.standaloneSetup(controller)
.alwaysDo(print())
.apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain))
.build();
MockitoAnnotations.initMocks(this);
}
I am still wresting with various annotations in setting up a test context under spring boot.
I have been referring to this article, which is refreshingly clear on how to deal with various contexts under Spring Boot. The problem remaining is that I cannot seem to find an annotation combination that will make the springSecurityFilterChain visible in both the main application context (driven from here):
#EnableAutoConfiguration
#ComponentScan
public class Application {
public static void main(String[] args) throws Exception {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
and from the test application context begun here:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {TestPersistenceConfig.class,MvcConfig.class,SecurityConfig.class},loader=AnnotationConfigContextLoader.class)
//#SpringApplicationConfiguration(classes = {TestPersistenceConfig.class,MvcConfig.class,SecurityConfig.class})
#WebAppConfiguration
public class ApplicationIntegrationTest {
MockMvc mockMvc;
#Autowired
private WebApplicationContext wac;
//#Resource(name="springSecurityFilterChain")
#Autowired
private FilterChainProxy springSecurityFilterChain;
#Autowired
private UserDao userDao;
#Autowired
private ClientDao clientDao;
#Autowired
private RoleDao roleDao;
UUID key = UUID.fromString("f3512d26-72f6-4290-9265-63ad69eccc13");
#Before
public void setup() {
// using the web application to initate the mock
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilter(springSecurityFilterChain).build();
// our other choice is using another controller config
//mockMvc = MockMvcBuilders.annotationConfigSetup(ExampleApplicationContext.class).build();
// here we should build up the data structure using hibernate
List<Client> clients = new ArrayList<>();
Client clientEN = new Client();
clientEN.setDeviceId("444444444");
clientEN.setLanguage("en-EN");
clientEN.setAgentId("444444444|68:5b:35:8a:7c:d0");
Client clientENDomain = clientDao.save(clientEN);
clients.add(clientENDomain);
List<Role> roles = new ArrayList<>();
Role roleUser = new Role();
roleUser.setRole("user");
Role roleUserDomain = roleDao.save(roleUser);
roles.add(roleUserDomain);
Role roleAdmin = new Role();
roleAdmin.setRole("admin");
Role roleAdminDomain = roleDao.save(roleAdmin);
roles.add(roleAdminDomain);
User user = new User();
user.setLogin("user");
user.setPassword("password");
user.setClients(clients);
user.setRoles(roles);
userDao.save(user);
}
#Test
public void thatViewBootstrapUsesHttpNotFound() throws Exception {
// testing that a correct login into the form will result in a cookie being set
MvcResult result = mockMvc.perform(post("/login")
.param("username", "user").param("password", "password")).andReturn();
Cookie c = result.getResponse().getCookie("my-cookie");
Cookie[] cookies = result.getResponse().getCookies();
for (int i = 0; i <= cookies.length; i++) {
System.out.println("cookie " + i + " name: " + cookies[i].getName());
System.out.println("cookie " + i + " value: " + cookies[i].getValue());
}
//assertThat(c.getValue().length(), greaterThan(10));
// No cookie; 401 Unauthorized
mockMvc.perform(get("/")).andExpect(status().isUnauthorized());
// With cookie; 200 OK
mockMvc.perform(get("/").cookie(c)).andExpect(status().isOk());
// Logout, and ensure we're told to wipe the cookie
result = mockMvc.perform(delete("/session")).andReturn();
c = result.getResponse().getCookie("my-cookie");
assertThat(c.getValue().length(), is(0));
}
}
By the way #SpringApplicationConfiguration doesn't seem to work in any circumstance, contrary to the doco. The security config is as follows:
#Configuration
#EnableWebMvcSecurity
#ComponentScan({
"com.touchcorp.touchpoint.security",
"com.touchcorp.touchpoint.service",
"com.touchcorp.touchpoint.model.dao"})
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
DeviceUsernamePasswordAuthenticationProvider customAuthenticationProvider;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.authenticationProvider(customAuthenticationProvider);
}
#Configuration
#Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
#Order(2)
#Configuration
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error=1")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/");
}
}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/")
.setCachePeriod(31556926);
}
}
Can anyone see why the springSecurityFilterChain is invisible ("No beans of FileterChainProxy type found"). Thanks, I'm pulling my hair out here.
I think I am just a bit unclear as to the purpose of all the annotations. The Spring Boot reference is good, but it doesn't really extend beyond an established baseline. It seems that as soon as you have to combine spring security, hibernate and mvc together, it starts to get complicated and its not clear as to what one is to do.
I would be worried about why #SpringApplicationConfiguration is not working because it is in extensive use elsewhere (e.g. in Spring Boot samples) and it works fine there. Maybe a classpath issue? How about linking to a complete project that others can try to reproduce your problem?
You have 2 different application contexts (one for the test and one in your Application) so it wouldn't be surprising if they behaved differently. In particular the Application has #EnableAutoConfiguration and you test (as far as we can see) does not, so there's one difference that's worth looking into. But nothing is obviously wrong with the test.
Here's an example of a test that autowires the Security filter: https://github.com/spring-projects/spring-security-oauth/blob/master/samples/oauth2/sparklr/src/test/java/org/springframework/security/samples/config/ApplicationConfigurationTests.java. It works. Here's another: https://github.com/cloudfoundry/uaa/blob/master/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/audit/AuditCheckMvcMockTests.java.
Thanks to you Dave Syer,
I have made a couple of changes that seem to resolve the various missing pieces:
a test class that begins with:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {TestApplicationConfig.class,TestPersistenceConfig.class,MvcConfig.class,SecurityConfig.class},loader=AnnotationConfigWebContextLoader.class)
#WebAppConfiguration
public class ApplicationIntegrationTest {
and a "marker" Config class, which acts as a component scanner:
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackages = {"com.touchcorp.touchpoint"})
public class TestApplicationConfig {
}
All pars seem to work aside from the data layer, which cannot find any of my domain objects, but this appears to be restricted to the JPA/Hibernate config, not so much an application problem.
Thanks again.
I have a Spring MVC 3.2 project that I would like to unit & integration tests. The problem is all the dependencies I have, makes testing extremely difficult even with Sprint-test.
I have a controller like this:
#Controller
#RequestMapping( "/" )
public class HomeController {
#Autowired
MenuService menuService; // will return JSON
#Autowired
OfficeService officeService;
#RequestMapping( method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE )
#ResponseBody
public AuthenticatedUser rootCall( HttpServletRequest request ) {
AuthenticatedUser authentic = new AuthenticatedUser();
Office office = officeService.findByURL(request.getServerName());
authentic.setOffice(office);
// set the user role to authorized so they can navigate the site
menuService.updateVisitorWithMenu(authentic);
return returnValue;
}
This will return a JSON object. I would like to test this call returns a 200 and the correct object with canned JSON. However, I have a lot of other classes called by those #Autowired classes, and even if I mock them like this:
#Bean public MenuRepository menuRepository() {
return Mockito.mock(MenuRepository.class);
}
this creates a lot of mocked classes. Here is how I am trying to test it:
#RunWith( SpringJUnit4ClassRunner.class )
#ContextConfiguration( classes = JpaTestConfig.class )
#WebAppConfiguration
public class HomeControllerTest {
private EmbeddedDatabase database;
#Resource
private WebApplicationContext webApplicationContext;
#Autowired
OfficeService officeService;
private MockMvc mockMvc;
#Test
public void testRoot() throws Exception { mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
.andExpect(content().contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8))
.andExpect(content().string(<I would like canned data here>));
}
I can go thru and setup a H2 embeddeddatabase and populate it, but I wonder if that is really a test of this controller or the application? Can anyone recommend some better approaches to this integration test? How does one write unit tests for controllers?
Thank you!
Check out the spring show case project and take a look at controller test cases you will be able to understand and see standard way of testing controllers. MappingControllerTests.java has some json based controller testing
Am new to Spring MVC, i have written web servise using spring MVC and resteasy. My controller is working fine, now need to write testcase but i tried writtig but i never succed am also getting problem in autowiring.
#Controller
#Path("/searchapi")
public class SearchAPIController implements ISearchAPIController {
#Autowired
private ISearchAPIService srchapiservice;
#GET
#Path("/{domain}/{group}/search")
#Produces({"application/xml", "application/json"})
public Collections getSolrData(
#PathParam("domain") final String domain,
#PathParam("group") final String group,
#Context final UriInfo uriinfo) throws Exception {
System.out.println("LANDED IN get****************");
return srchapiservice.getData(domain, group, uriinfo);
}
}
can anyone give me sample code for Test case in spring mvc.
"Spring-MVC" Test case could seem like this using mock objects, for example we want to test my MyControllerToBeTest:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("/spring.xml")
public class MyControllerTest {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MyControllerToBeTested controller;
private AnnotationMethodHandlerAdapter adapter;
#Autowired
private ApplicationContext applicationContext;
#Before
public void setUp() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
response.setOutputStreamAccessAllowed(true);
controller = new MyControllerToBeTested();
adapter = new AnnotationMethodHandlerAdapter();
}
#Test
public void findRelatedVideosTest() throws Exception {
request.setRequestURI("/mypath");
request.setMethod("GET");
request.addParameter("myParam", "myValue");
adapter.handle(request, response, controller);
System.out.println(response.getContentAsString());
}
}
but i don't have any experience with REST resource testing, in your case RestEasy.
If you want to test the full service inside the container you can have a look at the REST Assured framework for Java. It makes it very easy to test and validate HTTP/REST-based services.