I am trying to test that a particular method throws an expected exception from a method. As per JUnit4 documentation and this answer I wrote the test as:
@Test(expected=CannotUndoException.class)
public void testUndoThrowsCannotUndoException() {
// code to initialise 'command'
command.undo();
}
However, this code fails the JUnit test, reporting the thrown (and expected) exception as an error.
The method I'm testing has only this in the body:
public void undo() {
throw new CannotUndoException();
}
Furthermore, the following test passes:
public void testUndoThrowsCannotUndoException() {
// code to initialise 'command'
try {
command.undo();
fail();
} catch (CannotUndoException cue){
}
}
Meaning that the expected exception is actually thrown.
I am actually planning to change the method to actually do something, rather than just throw the exception, but it's got me curious as to what caused the problem, lest it should happen again in the future.
The following checks have been made:
- the CannotUndoException imported into the test case is the correct one
- version 4 of JUnit is the only one on my classpath
- a clean and build of Eclipse workspace did not change the outcome
I am using JUnit 4.1, and in the same test I am using Mockito.
What could be causing the erroneous failure?