3

The title explains my question 100%. Let assume there is @ControllerAdvice annotated class in Spring Boot/MVC. In my case it contains @ExceptionHandler annotations. Ok, I can do unit-test of this class (it returns formatted JSON with information from Exception class). It is easy - especially when using Spock.

But what about integration tests? The only way to test if my usage of Spring library is right is to create controller that only exists for testing purposes, add some methods to it that eg. throw exception of specific kind and see if it returns what I designed @ControllerAdvice to return. But it seems ugly - creating additional code only for testing of existing code.

So my questions is - how do You do integration-tests on @ControllerAdvice? Do You just do not do it, create special controller only to test @ControllerAdvice or just test it using existing controller providing it for example with wrong data that will result in exception being thrown (in my case, if it was @InitBinder methods we will check ModelAndView)?

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Chlebik
  • 646
  • 1
  • 9
  • 27

1 Answers1

0

For an integration test in Spring Framework the test should do the following:

  • Instantiate an application context. In your case the application context must contain the controller and the controller advice
  • Make a request on the HTTP endpoint defined by the controller
  • Assert the results

You can find more details of the integration testing in Spring here: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#spring-mvc-test-framework

  • 1
    I know that but in Your solution there is controller involved. And my question is - should I create separate controller for testing @ControllerAdvice classes or use existing ones? – Chlebik Jul 07 '16 at 11:02
  • I wouldn't create a new controller only for testing the advice, why not use existing ones? This way you can test the advice with the actual flow intended to work in the application. – Alexandru Marina Jul 07 '16 at 11:08
  • Let's just assume that I want to test handler for ValidationException. The only place in my app this exception is generated is when I try to access external system, get some data, then create an object and validate it. It is done mostly in `@Service` beans. So how do You propose to simulate such situation using existing controllers during integration testing? – Chlebik Jul 07 '16 at 11:18
  • In the application context of the integration test i would put a bean which is a mock of the service. That mock would raise an exception for any method call (using Mockito) and, if the setup is correct, the advice would catch it. – Alexandru Marina Jul 07 '16 at 12:00