title: Spring Boot: How to test a service in JUnit with @Validated annotation?
body: <p>I'm trying to build a set of constraint validators for my Spring Boot application. I want to build some validation annotations like <code>@NotNull</code>. <strong>Btw: The validations should support validation groups.</strong></p>
  
  <p>So I have a simple item model with a validation annotation:</p>
  
  <pre><code>public class Item {
      @NotNull(groups=OnCreate.class) // Not Null on validation group 'OnCreate'
      private String mayNotBeNull;
  
      // Constructors and getter/setter stuff.
  }
  </code></pre>
  
  <p>Then I wrapped the persistence logic using a <strong>validated</strong> service:</p>
  
  <pre><code>@Service
  @Validated
  public class MyService {
      public Item create(@Validated(OnCreate.class) Item item) {
          Item savedItem = repository.save(item);
          return savedItem;
      }
  }
  </code></pre>
  
  <p>Now I want to test this service without starting a full blown MVC test (which would start all REST controllers and stuff I do not need).</p>
  
  <p>I started to write my test:</p>
  
  <pre><code>@ContextConfiguration(classes = {
  ItemRepository.class, MyService.class, LocalValidatorFactoryBean.class
  })
  @RunWith(SpringRunner.class)
  public class PlantServiceTest {
  
    @MockBean
    private ItemRepository repository;
  
    @Autowired
    private MyService service;
  
    @Autowired
    private Validator validator;
  
    @Test
    public void shouldDetectValidationException() {
          // ... building an invalid item
          Item item = new Item();
          item.setMayNotBeNull(null); // &lt;- This causes the validation exception.
          validator.validate(item, OnCreate.class);
    }
  
    @Test
    public void shouldAlsoDetectValidationException() {
          // ... building an invalid item
          Item item = new Item();
          item.setMayNotBeNull(null); // &lt;- This should cause the validation exception.
          service.create(item); // &lt;- No validation error. Service is not validating.
    }
    }
  </code></pre>
  
  <p>The method <code>shouldThrowValidationException</code> detects the validation error, because the field value in item is <code>null</code>. </p>
  
  <p>The method <code>shouldAlsoDetectValidationException</code> does not detect the validation error. </p>
  
  <p>I think I missed something when configuring the context. The service object is not extended by the validation logic. </p>
  
  <p>How can I configure the test so that the autowired services are decorated with the validation logic provided by <code>@Validated</code>?</p>