我正在使用Hibernate保存和加载一个@ manymany关系。我对这些进行了单元测试,它们工作正常,我可以在数据库中正确地看到记录。
我正试图写一个JUnit测试来更新这些@ manymany项目。
当我从测试中删除@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
但那没有用。
我怎么测试一个更新,当我被诅咒如果我做和诅咒如果我不做?谢谢你!
您可以用@Commit
注释您的测试方法:
@Commit
@Test
@Transactional
void testProcessWithoutRollback() {
// ...
}
查看文档的这一部分以获取更多信息:https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html spring-testing-annotation-commit
您可以尝试用
注释您的测试方法@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void testMethod(String user) {
// ...
}
据我所知,spring默认处理集成测试,因此在单元测试之后,数据库更改可以回滚,以防止其他单元测试受到影响。这里不是100%确定,但可能值得一试:)