【发布时间】:2020-02-21 23:20:27
【问题描述】:
我正在编写单元测试来检查输入验证是否在我的 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