【发布时间】:2019-05-29 02:33:31
【问题描述】:
我想编写事务性单元测试,以便在方法完成时回滚更改,但由于使用休眠和 JPA 存储库,我遇到了问题。由于某些原因,我在尝试使用 @Transactional 注释 @Test 方法时得到 UnsupportedOperationException
这是我正在尝试测试孤儿删除逻辑的代码,一切正常,但我不希望这些实体在方法完成后出现在数据库中。
@RunWith(SpringRunner.class)
@SpringBootTest
public class NotificationGroupServiceTest {
@Autowired
private NotificationGroupService notificationGroupService;
private NotificationGroupEntity groupEntity;
private Long groupId;
private NotificationCriterionEntity notificationCriterionEntity;
private HistoricalNotificationEntity historicalNotificationEntity;
@Before
public void initializeEntities() {
groupEntity = new NotificationGroupEntity();
groupEntity = notificationGroupService.createOrUpdate(groupEntity);
groupId = groupEntity.getId();
notificationCriterionEntity = new NotificationCriterionEntity();
historicalNotificationEntity = new HistoricalNotificationEntity();
notificationCriterionEntity.setNotificationGroupId(groupId);
historicalNotificationEntity.setNotificationGroupId(groupId);
groupEntity.setHistoricalNotifications(Arrays.asList(historicalNotificationEntity));
groupEntity.setActiveNotificationsList(Arrays.asList(notificationCriterionEntity));
}
@Test
public void testOrphanRemoval() {
notificationGroupService.createOrUpdate(groupEntity);
Optional<NotificationGroupEntity> optionalNotificationGroupEntity =
notificationGroupService.findById(groupId);
Assert.assertTrue(optionalNotificationGroupEntity.isPresent());
groupEntity = optionalNotificationGroupEntity.get();
Assert.assertEquals(1, groupEntity.getActiveNotificationsList()
.size());
Assert.assertEquals(1, groupEntity.getHistoricalNotifications()
.size());
Assert.assertEquals(groupEntity.getActiveNotificationsList()
.get(0)
.getNotificationGroupId(), groupId);
Assert.assertEquals(groupEntity.getHistoricalNotifications()
.get(0)
.getNotificationGroupId(), groupId);
groupEntity.setActiveNotificationsList(Arrays.asList());
groupEntity.setHistoricalNotifications(Arrays.asList());
notificationGroupService.createOrUpdate(groupEntity);
optionalNotificationGroupEntity =
notificationGroupService.findById(groupId);
Assert.assertTrue(optionalNotificationGroupEntity.isPresent());
groupEntity = optionalNotificationGroupEntity.get();
Assert.assertEquals(0, groupEntity.getActiveNotificationsList()
.size());
Assert.assertEquals(0, groupEntity.getHistoricalNotifications()
.size());
}
}
【问题讨论】:
-
我也有同样的问题。你解决了吗?
标签: java spring hibernate spring-boot transactional