Spring Boot:如何使用 @Validated 注释在 JUnit 中测试服务?

UNI*_*orn 3 spring-mvc spring-boot

我正在尝试为我的 Spring Boot 应用程序构建一组约束验证器。我想构建一些验证注释,例如@NotNull. 顺便说一句:验证应该支持验证组。

所以我有一个带有验证注释的简单项目模型:

public class Item {
    @NotNull(groups=OnCreate.class) // Not Null on validation group 'OnCreate'
    private String mayNotBeNull;

    // Constructors and getter/setter stuff.
}
Run Code Online (Sandbox Code Playgroud)

然后我使用经过验证的服务包装了持久性逻辑:

@Service
@Validated
public class MyService {
    public Item create(@Validated(OnCreate.class) Item item) {
        Item savedItem = repository.save(item);
        return savedItem;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想测试这个服务而不启动一个完整的 MVC 测试(这将启动所有 REST 控制器和我不需要的东西)。

我开始写我的测试:

@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); // <- 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); // <- This should cause the validation exception.
        service.create(item); // <- No validation error. Service is not validating.
  }
  }
Run Code Online (Sandbox Code Playgroud)

该方法shouldThrowValidationException检测到验证错误,因为 item 中的字段值为null

该方法shouldAlsoDetectValidationException不检测验证错误。

我想我在配置上下文时错过了一些东西。验证逻辑不扩展服务对象。

如何配置测试,以便使用 提供的验证逻辑装饰自动装配的服务@Validated

Sim*_*lli 5

@Validated 在参数上无法按预期工作。您必须在参数上使用 @Valid 并在方法或类级别添加带有组的 @Validated 。

它是这样工作的:

@Service
@Validated
public class MyService {

    @Validated(OnCreate.class)
    public Item create(@Valid Item item) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,我发现无法在参数级别设置组。

如果要在 Spring 单元测试中测试验证逻辑,则必须通过以下方式导入 ValidationAutoConfiguration 类:

@Import(ValidationAutoConfiguration.class)
Run Code Online (Sandbox Code Playgroud)

  • 是的,您必须使用 SpringBootTest 注释您的测试才能完全启动并运行 Spring Boot 或在您的测试中创建 MethodValidationPostProcessor (2认同)
  • 就我而言,我想要使用 Spring Boot 中使用 @DataJpaTest 的测试类来验证 @Service 类。我必须将 @Import(ValidationAutoConfiguration::class) 添加到类中以进行验证(即,要定义 MethodValidationPostProcessor) (2认同)