【发布时间】:2013-08-19 04:22:45
【问题描述】:
在一个简单的项目中,我喜欢测试 @NotNull 验证(以及其他一些自定义验证)。
因此,我编写了一些执行此操作的单元测试:@Test(expect=ValidationException.class
一个最小的 mavinized 示例来重现我在 github 上上传的问题:
-
https://github.com/d0x/questions/tree/master/givenIdValidation
执行
mvn clean test
我认为如果@Id 是生成值,它会很好地工作。但是如果@Id是系统给出的,则忽略验证。
这些类将显示重现问题的最小设置:
两个实体(一个有生成值,一个没有生成值:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class GeneratedId {
@Id
@GeneratedValue
private Long id;
@NotNull
private String content;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class GivenId {
@Id
private Long id;
@NotNull
private String content;
}
单元测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:/applicationContext.xml")
@Transactional
@ActiveProfiles("embedded")
public class MyEntityTest
{
@Autowired GeneratedIdService generatedIdService;
@Autowired GivenIdService givenIdService;
// This test will pass
@Test(expected = ValidationException.class)
public void shouldNotAllowNullValues1()
{
this.generatedIdService.save(new GeneratedId());
}
// This test will fail
@Test(expected = ValidationException.class)
public void shouldNotAllowNullValues2()
{
this.givenIdService.save(new GivenId(1L, null));
}
}
这是样板服务和存储库
public interface GeneratedIdRepository extends JpaRepository<GeneratedId, Long> {
}
public interface GivenIdRepository extends JpaRepository<GivenId, Long> {
}
@Service
public class GeneratedIdService {
@Autowired GeneratedIdRepository repository;
public GeneratedId save(final GeneratedId entity) {
return this.repository.save(entity);
}
}
@Service
public class GivenIdService {
@Autowired GivenIdRepository repository;
public GivenId save(final GivenId entity) {
return this.repository.save(entity);
}
}
目前我正在使用 Spring 3.1.4、Spring-Data 1.3.4、Hibernate 4.1.10 和 Hibernate-Validator 4.2.0。
有什么建议的方式跳过验证?
编辑 1:
我在两个实体上都尝试了没有lombok,仍然出现错误。
【问题讨论】:
标签: java jpa spring-data spring-data-jpa lombok