Я немного поиграл с этой проблемой.
Ваш код мне подходит: убедитесь, что реализация UserService
также имеет аннотации проверки.
Убедитесь, чтовы позволяете Spring создавать Бин;он должен работать так, как вы ожидаете.
Пример
Определение сервиса
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Validated
public interface GreetingService {
String greet(@NotNull @NotBlank String greeting);
}
Реализация сервиса
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Service
public class HelloGreetingService implements GreetingService {
public String greet(@NotNull @NotBlank String greeting) {
return "hello " + greeting;
}
}
Тестовый случай
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import javax.validation.ConstraintViolationException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@SpringBootTest
class HelloGreetingServiceTest {
@Autowired
private GreetingService helloGreetingService;
@Test
void whenGreetWithStringInput_shouldDisplayGreeting() {
String input = "john doe";
assertEquals("hello john doe", helloGreetingService.greet(input));
}
@Test
void whenGreetWithNullInput_shouldThrowException() {
assertThrows(ConstraintViolationException.class, () -> helloGreetingService.greet(null));
}
@Test
void whenGreetWithBlankInput_shouldThrowException() {
assertThrows(ConstraintViolationException.class, () -> helloGreetingService.greet(""));
}
}
Тест-кейсы для меня зеленые.
Github: https://github.com/almac777/spring-validation-playground
Источник: https://www.baeldung.com/javax-validation-method-constraints
HTH!