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

情到浓时终转凉″ 提交于 2019-12-05 02:12:46

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.

Your test code looks ok to me.

Check that you're running with a junit 4 testrunner, not a junit 3.8 testrunner - this could very well be the culprit here (try launching from the command line or just visually inspect the command line when running your test). The classpath of your testrunner may not be the same as your project classpath

This is particularly the case inside IDE's. Alternately you could also try to push to junit 4.4 and see if that solves your problem. (junit 4.5 may cause other problems).

I had a similar problem and I fixed it by adding the annotation

@RunWith(JUnit4ClassRunner.class)

Which tells the unit tester to run it with the 4er version of Junit

Curious.

I wrote three classes:

An UndoCommand:

public class UndoCommand
{
    public void undo()
    {
        throw new CannotUndoException();
    }
}

A CannotUndoException:

// Note: extends the unchecked superclass RuntimeException
public class CannotUndoException extends RuntimeException
{
    public CannotUndoException()
    {
        super();
    }

    public CannotUndoException(String message)
    {
        super(message);
    }

    public CannotUndoException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public CannotUndoException(Throwable cause)
    {
        super(cause);    
    }
}

And a JUnit 4.4 test class:

import org.junit.Test;

public class UndoCommandTest
{
    @Test(expected=CannotUndoException.class)
    public void testUndo()
    {
        UndoCommand command = new UndoCommand();

        command.undo();
    }
}

Works perfectly - all tests pass, "green" result.

If I remove the (expected=...) from the annotation the test fails, as expected.

I'm using Sun JDK 6, JUnit 4.4 and IntelliJ 7.0.5.

How does yours differ?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!