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:
I am using JUnit 4.1, and in the same test I am using Mockito.
What could be causing the erroneous failure?
I have found the problem.
The TestRunner I was using was the correct one (JUnit 4), however, I declared my test class as:
public class CommandTest extends TestCase
Which I assume is causing the test runner to treat it as a JUnit 3 test. I removed extends TestCase
and received the expected results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With