0

I have @transactional method that seems to be working (rolling back) if run the actual service and provide inputs that would cause a run-time error. If I create a Test for that method that throws a run-time error it doesn't seem to rollback anymore. Any idea why this doesn't work while testing?

it's somthing like:

@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
    }
}
Robert Petty
  • 197
  • 1
  • 3
  • 17
  • Possible duplicate of [JUnit tests always rollback the transactions](https://stackoverflow.com/questions/9817388/junit-tests-always-rollback-the-transactions) – sovannarith cheav Oct 18 '19 at 02:58

1 Answers1

0

Just add annotation Rollback and set the flag to false.

   @Test
   @Rollback(false)
sovannarith cheav
  • 743
  • 1
  • 6
  • 19