gpt4 book ai didi

java - 为什么我的@Transactional方法在测试时没有回滚?

转载 作者:行者123 更新时间:2023-12-01 22:55:15 25 4
gpt4 key购买 nike

如果运行实际服务并提供会导致运行时错误的输入,我有 @transactional 方法,该方法似乎正在工作(回滚)。如果我为该方法创建一个抛出运行时错误的测试,它似乎不再回滚。知道为什么这在测试时不起作用吗?

它是这样的:

@Service
public class SampleServiceImpl implements SampleService {

private final RepoA repoA;
private final RepoB repoB;

public SampleServiceImpl(RepoA repoA, RepoB repoB) {
this.repoA = repoA,
this.repoB = repoB
}

@Transactional
@Override
public void addItems() {
repoA.save(new ItemA(1,'name1')); //works
repoB.save(new ItemB(2,'name2')); //throws run-time error
}
}
@RunWith(SpringRunner.class)
@DataJpaTest
public class Tests {

@Autowired
private RepoA repoA;

@Mock
private Repob repoBMock;

@Test
public void whenExceptionOccurrs_thenRollsBack() {
var service = new SampleService(repoA, repoBMock);
Mockito.when(repoBMock.save(any(ItemB.class))).thenThrow(new RuntimeException());
boolean exceptionThrown = false;
try {
service.addItems()
} catch (Exception e) {
exceptionThrown = true;
}

Assert.assertTrue(exceptionThrown);
Assert.assertFalse(repoA.existsByName('name1')); // this assertion fails because the the first item still exists in db
}
}

最佳答案

只需添加注释 Rollback 并将标志设置为 false。

   @Test
@Rollback(false)

关于java - 为什么我的@Transactional方法在测试时没有回滚?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58443290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com