侦测单元测试-LazyInitializationException:无法延迟初始化集合

时间:2019-01-08 20:12:20

标签: hibernate spring-boot junit

我正在尝试测试一些端点,但是为此,我需要“模拟”一些第三方webhooks。除了我正在使用服务为传入的Webhook更新数据的那一部分之外,其他所有东西都正常运行。

我得到的异常是:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: mz.server.hibernate.model.PlaceSubscriptionEntity.placeSubscriptionEvents, could not initialize proxy - no Session

    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:597)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:216)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:576)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:147)
    at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:188)
    at java.util.Spliterators$IteratorSpliterator.estimateSize(Spliterators.java:1821)
    at java.util.Spliterator.getExactSizeIfKnown(Spliterator.java:408)
    at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:497)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.MatchOps$MatchOp.evaluateSequential(MatchOps.java:230)
    at java.util.stream.MatchOps$MatchOp.evaluateSequential(MatchOps.java:196)

我所有的实时测试都在这里扩展了这个抽象类:

@FlywayTest
@RunWith(SpringRunner.class)
@SpringBootTest(
        webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
        properties = "spring.profiles.active=test"
)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
@TestExecutionListeners({
        DependencyInjectionTestExecutionListener.class,
        FlywayTestExecutionListener.class
})
public abstract class AbstractLiveTest {

    @Value("${security.jwt.client-id}")
    protected String clientId;

    @Value("${security.jwt.client-secret}")
    protected String clientSecret;

    @Value("${security.jwt.client-secret-plain}")
    protected String clientSecretPlain;

    @Value("${server.port}")
    protected Integer serverPort;

    @Autowired
    protected TestRestTemplate restTemplate;

}

根据另一个答案的建议,我试图将@Tranasctional添加到我的单元测试方法中:

@Test
@Transactional
public void whenCreateSubscription() throws Exception {
     // ..
}

但这没有任何作用。

有什么想法吗?

0 个答案:

没有答案