我正在使用 Hibernate 保存和加載 @ManyToMany 關系。我對這些進行了單元測驗,它們作業正常,我可以在資料庫中正確查看記錄。
我正在嘗試撰寫一個 JUnit 測驗來更新這些 @ManyToMany 專案。
當我從測驗中洗掉 @Transactional 時,我得到:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.foo.bar.PrimaryObject.manyToManySet, could not initialize proxy - no Session
但是當我將 @Transactional 添加到測驗中時,我得到:
Rolled back transaction for test: [DefaultTestContext@8bb5c2a testClass = PrimaryObjectManagerTest, testInstance = com.foo.bar.dataaccess.PrimaryObjectManagerTest@4d4337f9, testMethod = updatePrimaryObject@PrimaryObjectManagerTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@a5df98c testClass = AnnouncementManagerTest, locations = '{}', classes = '{class com.foo.bar.DataAccessApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@156b88f5, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@71def8f8, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@1da2cb77, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@1e04fa0a, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@5a56cdac, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@36b4cef0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]
所以我無法驗證資料庫是否有任何真正的變化!
我嘗試添加到測驗類:
@RecordApplicationEvents
但這無濟于事。
如果我這樣做該死,如果我不這樣做該死,我該如何測驗更新?謝謝!
uj5u.com熱心網友回復:
您可以使用注釋來注釋您的測驗方法@Commit:
@Commit
@Test
@Transactional
void testProcessWithoutRollback() {
// ...
}
查看檔案的這一部分以獲取更多資訊: https ://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#spring-testing-annotation-commit
uj5u.com熱心網友回復:
您可以嘗試使用注釋您的測驗方法
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void testMethod(String user) {
// ...
}
據我記得spring默認處理集成測驗,以便在單元測驗后資料庫更改可以回滾以防止其他其他單元測驗受到影響。這里不是 100% 肯定,但可能值得一試:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/459055.html
