3

I have to make a test the idempotency of a method.

Let us say i have class Person with following method:

    public String doSomething(String a){ 
//do some stuff
personDao.delete(a)
}

and I need to test when something goes wrong before the delete that the next time you call the method doSomething it will create the same result as you wanted when it should have run correctly the first time. This could happen for example when you run a script that calls that method but fails for example by stopping the script. When you run the script the following time it should have give the same result without the failure.

Can you do this in a unit test?

Thanks in advance

user1345883
  • 451
  • 1
  • 8
  • 24

2 Answers2

3

The test should run the method twice. The outcome / results should be identical in both cases. It's as simple as that really.

Pseudocode:

setupException();
doSomething(a);
assertOutcome();
doSomething(a);
assertOutcome();
Stewart
  • 17,616
  • 8
  • 52
  • 80
  • But I need to simulate an exception before the delete.. because the delete will delete the database record with id a, and that could break something in the do some stuff area – user1345883 Oct 10 '14 at 12:05
  • That's what the setup() method is for - to setup your exception. – Stewart Oct 10 '14 at 14:51
1

So the first part of the answer is to use a mock for the DAO. Write two tests, one where the method is called twice and the DAO doesn't throw an exception. The other where the DAO throws the exception on the first call to it.

The expected behavior in these two cases depends on your DAO. Is it OK to call delete on your DAO for a value that has already been deleted? If so, great. Expect two calls. If not, then you need logic to check for the state.

John B
  • 32,493
  • 6
  • 77
  • 98