测试 Spring Data Repository 在提交无效(违反验证)实体时失败

Test Spring Data Repository to fail upon submission of invalid (Validation violation) Entity

我正在尝试测试 Spring 数据存储库,特别是测试在传递带有错误参数的实体时会抛出的异常。实体使用 Java Bean 验证注释 @NotNull@Email

进行注释
@SpringBootTest(classes = PatientPKServiceApplication.class)
@RunWith(SpringRunner.class)
@DataJpaTest
public class PatientPKRepositoryTest {

@Autowired
private PatientPKRepository repository;


@Rule
public ExpectedException thrownException = ExpectedException.none();


 @Test
public void newEntityWithInvalidParametersShouldThrownConstraintViolations() throws Exception {
    this.thrownException.expect(ConstraintViolationException.class);
    this.repository.save(new PatientPK(null, null, null));
}

存储库是

public interface PatientPkRepository extends JpaRepository<PatientPk, Long> {
}

测试失败,

java.lang.AssertionError: Expected test to throw an instance of javax.validation.ConstraintViolationException

    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.rules.ExpectedException.failDueToMissingException(ExpectedException.java:263)
    at org.junit.rules.ExpectedException.access0(ExpectedException.java:106)

测试此行为的最佳方法是什么?我不想手动验证。


更新解决方案:正如 JB Nizet 所建议的(请参阅下面的答案),我们需要确保 Persistence Context 实际上已被刷新。将 repository.save 更改为 repository.saveAndFlush() 成功了。

The documentation 说:

By default, data JPA tests are transactional and roll back at the end of each test.

因此,由于您的测试是事务性的,并且由于它回滚,并且由于您从不刷新任何地方,因此 save() 操作实际上从未尝试写入数据库,并且从未验证在刷新之前执行的验证约束.