我想编写事务单元测试,以便在方法完成时回滚更改,但由于使用 hibernate 和 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());
}
}
最佳答案
使用@After
注释来指示在每个@Test
之后运行的方法。
像这样的全套注释是:
@BeforeClass
- 在所有@Tests
运行之前@Before
- 在每个@Test
运行之前@After
- 在每个@Test
运行之后@AfterClass
- 在所有@Tests
运行之后
如果您询问如何将特定的拆卸方法与特定的 @Test 方法关联起来,则不需要注释:只需在测试方法的末尾在 finally 中调用它即可。
你的测试类应该是:
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@ContextConfiguration("classpath:/spring-beans.xml")
public class NotificationGroupServiceTest {
....
}
关于java - 使用 spring boot 和 hibernate jpa 存储库进行事务测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54006432/