0

I cant stop myself for asking this question as SO is not an alternative for search engine, as we are exhausted searching the right content to start testing a Spring MVC application. We are very new to spring and unit testing. Please provide us links for step-by-step tutorial(if any) for Spring REST services testing and Controller testing and Spring security testing.

Please Help.

Thanks in advance.

gurusai
  • 153
  • 4
  • 16

1 Answers1

3

The controller.

If you want to test the code of the controller itself (returning correct ModelAndView or ModelMap), you can easily write some unit tests. I usually use the spring-test and junit for this.

Then I write my test like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-test-beans.xml")
public class FormControllerTest {

        @Autowired
        private MyController controller;

        @Test
        public void testFirstAction() {
                ModelMap model = new ModelMap();
                assertEquals("result", controller.firstAction("data", model));
                assertEquals("test", model.get("data"));
        }
}

So this way I test if the view/model is correct. If you want to see if the web page itself is correctly and uses the correct action, you might want to look at Selenium integration testing (if it's a webpage, not a REST service).


Spring security

To test Spring security, you probably want to mock the SecurityContextHolder. Here you can find the details of the current user, so you can also create mocks (with a mocking framework like Mockito or EasyMock) and make it look like you're logged in as a specific user. Some more information about it can be found here (also some answers show you how you can do it with a specific mocking framework).

Same as with my answer about the controller, if you want to test the total picture, you want to use integration testing (with Selenium for example).


REST service

The REST service itself (not the controller) is not something harder to test since it's more an integration test than a unit test. I think the best way to test this is to create a REST client (can be done with JAX-RS frameworks like RESTEasy or Apache CXF) and to test the results you get with the REST client.

This is usually easier to do when you defined your REST service with JAX-RS (and not with Spring MVC), but it's not impossible. If you don't want to create interfaces and extra domain classes, then you can also use the Apache HttpClient. I also found an example of how to use it here.

Community
  • 1
  • 1
g00glen00b
  • 41,995
  • 13
  • 95
  • 133