I’m trying to write a unit-test to verify that it’s impossible to create an instance of a certain object with a negative value.
My first test works OK as expected – it should pass.
My second test produces the IllegalArgumentException as expected, however the @Test(expected=IllegalArgumentException.class) does not absorb the error as I expected it to. In fact the test appears to behave exactly as if the @Test line were not there at all!
So what am I doing wrong?
package numbers;
import org.junit.Test;
import junit.framework.TestCase;
public class TestPositiveMoney extends TestCase {
public void testConstructFromLong( ) {
// Works OK
PositiveMoney x0 = new PositiveMoney( 3L );
}
@Test(expected=IllegalArgumentException.class)
public void testConstructInvalid( ) {
// This statement is intended to fail
PositiveMoney x0 = new PositiveMoney( -3L ); // Illegal
}
}
FYI, the second test produces the following TB:
java.lang.IllegalArgumentException: Negative value -3 not allowed
at numbers.PositiveMoney.<init>(PositiveMoney.java:48)
at numbers.TestPositiveMoney.testConstructInvalid(TestPositiveMoney.java:13)
extends junit.framework.TestCaseis a JUnit 3 technique.@Test(expected=IllegalArgumentException.class)is for JUnit 4.It seems you’re using a test runner from JUnit 3. Try the following:
@Testto your first testextends TestCaseclauseIf it doesn’t help—especially if the tests are not run any more—check what JUnit version you’re using.
If you use maven, try
-Xcommand-line switch.