@DataJpaTest用于失败测试案例

时间:2019-08-14 08:50:51

标签: hibernate spring-boot spring-data-jpa

@DataJpaTest上的任何人都可以给出示例代码片段,用于故障测试用例以及预期的异常。 @DataJpaTest默认情况下会应用事务,那么在这种情况下,我们需要使用@Transactional(propgation = Propogation.Not_Supported)。请提供以上所有内容的代码段示例。预先谢谢你...

1 个答案:

答案 0 :(得分:0)

在此示例中,我有一个实体LearningContent,其名称字段未设置为不可空。

    @Test(expected = DataIntegrityViolationException.class)
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void failLearningContentMissingName() {

        LearningProgram learningProgram = new LearningProgram();
        learningProgram.setBusinessReference(new BusinessReference("hello"));
        final BusinessIdentifier bid = BusinessIdentifier.generate();
        learningProgram.setBusinessIdentifier(bid);
        learningProgram.setName(new Localized("hello.learningprogram"));

        LppIntent intent = new LppIntent();
        intent.setBusinessReference(new BusinessReference("intent"));
        intent.setName(new Localized("intent"));
        learningProgram.addIntent(intent);

        LppLearningContent learningContent = new LppLearningContent();
        learningContent.setBusinessReference(new BusinessReference("learningContent"));
        learningContent.setContent("Hello world".getBytes(StandardCharsets.UTF_8));
        learningContent.setDuration(5L);
        intent.addLearningContent(learningContent);

        learningContent.tag("meow");

        learningProgramRepository.save(learningProgram);

    }