@ Valid不会在@Repository中触发验证

问题描述 投票:1回答:1

我正在编写单元测试以检查输入验证是否可以在我的Spring信息库中使用,但看起来不像它。

保持简单,我有一个Repository类:

@Repository
public class CustomerRepository {
    // Java client for Redis, that I extend as JedisConnector in order to make it a Bean
    private Jedis jedis;

    @Autowired
    public CustomerRepository(JedisConnector jedis) {
        this.jedis = jedis;
    }

    private <S extends Customer> S save(@Valid S customer) throws CustomerException {
        try {
            this.jedis.set(...);  // writing to Redis (mocked in test)
            return customer;
        } catch (JsonProcessingException e) {
            throw new CustomerException(e.toString());
        }
    }
}

这使用以下模型类:

@AllArgsConstructor
@NoArgsConstructor
@Data // from Lombok
public class Customer {
    @Email(message = "Email must be valid.")
    private String identifier;

    @NotBlank(message = "Password cannot be null or empty string.")
    private String password;

    @URL(message = "URL must be a url.")
    private String url;
}

所以我写了这样的单元测试,希望它会引发一些我可以断言的异常:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {JedisConnector.class})
public class CustomerRepositoryTest {
    // Cannot autowire because dependent bean needs to be configured
    private CustomerRepository customerRepository;

    @MockBean
    JedisConnector jedisConnector;

    @Before
    public void setUp() {
        // Configure Mock JedisConnector
        MockitoAnnotations.initMocks(this);
        Mockito.when(jedisConnector.select(anyInt())).thenReturn("OK");

        // Manually wire dependency
        customerRepository = new CustomerRepository(jedisConnector);
    }


    @Test
    public void saveShouldFailOnInvalidInput() throws CustomerException {
        Mockito.when(jedisConnector.set(anyString(), anyString())).thenReturn("OK");
        // Blatantly invalid input
        Customer customer = new Customer("testemail", "", "testurl");
        customerRepository.save(customer);
    }
}

但是它只是运行,仅输出调试消息(我在此问题中省略了)。 如何执行验证?如果可能,我想避免在存储库的每个方法中显式调用验证器。

[我已经在网上看到了许多尝试复制的示例(从Baeldung到DZone,当然在这个网站上还有很多问题,包括this interesting one),但仍然没有成功。我想念什么?

java spring-boot unit-testing bean-validation jedis
1个回答
1
投票

好像您想通过使用integration test来实现repository,以便通过显示javax.validation.ConstraintViolationException来抛出must not be blank,但是如果您只想测试那些验证,则必须使用通过以下方式验证者:

1.-添加以下依赖项:

<dependency> 
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.13.Final</version>
</dependency> 

2.-为Customer字段添加自定义验证测试

import javax.validation.Validation;
import javax.validation.Validator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
public class CustomerValidationTest {

    private Validator validator;

    @Before
    public void setupValidatorInstance() {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    @Test
    public void whenNotEmptyPassword_thenNoConstraintViolations() {
        Customer customer = new Customer();
        customer.setPassword("");
        Set<ConstraintViolation<Customer>> violations = validator.validate(customer);

        assertThat(violations.size()).isEqualTo(1);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.