Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cause of an unexpected behaviour using JUnit 4's expected exception mechanism?

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?

like image 637
Grundlefleck Avatar asked Dec 27 '08 19:12

Grundlefleck


1 Answers

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.

like image 59
Grundlefleck Avatar answered Oct 20 '22 20:10

Grundlefleck