我正在使用h2在spring数据中测试存储库,我想要测试的确切功能是当存储库尝试保存实体时对一个字段长度的约束。
例如,实体类看起来像这样:
@Entity
@Table(name = "page")
public class Page{
@Id
@Size(max=5)
@Column(name="name")
private String name;
//... setters and getters.
从服务中,我调用存储库:
public class PageServiceImpl implements PageService{
private PageRepository repository;
public PageServiceImpl(PageRepository repository){
this.repository = repository;
}
@Override
public save(Page page){
repository.save(page);
}
}
服务测试:
@RunWith(SpringRunner.class)
@DataJpaTest
public class PageServiceImplIT{
private PageService service;
//...
@Test
public void shouldCrashWhenSaving(){
Page page = new Page();
page.setName("VeryLongString");
service.save(page); // It should throw an Exception, Name is too
// long
}
//..
当我测试上面的代码时,成功传递,但我期待一个ConstraintViolationException或某种类型的异常,就像我尝试将实体保存到SQL数据库时一样。我做错了什么?
更新
我意识到如果我尝试获取数据库中所有寄存器的列表,我会得到异常:
@Test
public void shouldCrashWhenSaving(){
Page page = new Page();
page.setName("VeryLongString");
service.save(page);
List<Page> pages = service.findAll();//This causes the exception
//to be thrown.
}
这是堆栈跟踪的第一部分:
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.DataException: could not execute statement
然而,我想要的是在存储库保存实体后立即获取异常。