首页 > 解决方案 > @DataJpaTest 用于失败测试用例

问题描述

任何人都可以在@DataJpaTest 上为失败测试用例提供示例代码片段以及预期的异常。@DataJpaTest 默认应用事务,在这种情况下我们需要使用@Transactional(propgation=Propogation.Not_Supported)。请提供一个包含以上所有内容的代码片段示例。提前谢谢你...

标签: hibernatespring-bootspring-data-jpa

解决方案


这是一个示例,其中我有一个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);

    }


推荐阅读