java123999
java123999

Reputation: 7394

How to purposely throw an error to test database rollback?

I have the following code within my application:

try {
    //start transaction
    repository.startTransaction();

    //carry out deletion logic
    repository.deletedata()

    //commit all 3 transactions
    repository.commitTransaction();

} catch (Exception e) {    
    repository.rollback();
}

How can I intentionally throw an error within this code to test if the data is correctly being rolled back?

Upvotes: 1

Views: 533

Answers (1)

GhostCat
GhostCat

Reputation: 140465

You are getting testing wrong here.

You should be doing two things instead: you write a test that makes sure that your rollback method does what it promises to do. You test that on the side.

Then you have another unit test that simply makes sure that whenever there is an exception within your try block that the expected call to rollback takes place.

If you really want to do a functional test that does end-2-end testing including rollback, then you have to add some injection mechanism, something like:

interface ErrorInject {
  void throwException();
}

and in your try block, you would have something like:

try {
  repository.startTransaction();
  inject1.throwException();
  repository.deletedata()
  inject2.throwException();
  repository.commitTransaction();
}

and by default, those two "inject" objects simply do nothing; but for your test case, you make sure that one of those two objects really throws an exception.

But of course - you don't want to do something like that in your production code. So - you better step back and think if my first suggestion works for you.

One alternative could be aspect oriented programming; which might allow you to use some annotation for example to instruct your framework to fail at a certain method call. But as said: you shouldn't pollute your production code with "testing aspects".

Upvotes: 1

Related Questions