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

就像这样:

@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)

09-30 09:35