I'm trying to ensure that a parameter can't be null by adding an assert statement at the top of the method.
When unit testing, I'm trying to declare that the AssertError is expected, but it still gets r开发者_StackOverflowecognized as a failed test even though it's behaviour is correct (AssertError is getting thrown).
class ExampleTest {
@Test(expected=AssertError.class)
public void testAssertFails() {
assert 0 == 1;
}
}
You probably need to enable assertions with the -ea
JVM argument, since they're off by default. When the assertions are disabled, then the assert
won't throw an exception if it fails.
If you're running this in Eclipse you can edit your Installed JRE in preferences to add this as an argument, or you add it to the run configuration for your tests.
Also, the exception thrown is AssertionError
, not AssertError
.
The problem is, the exception class is not called AssertError, but AssertionError check out the Java API Javadoc.
Probably not a good idea to mix JVM-level assertions with JUnit assertions. That said, here's how it was done before we had annotations. You might consider doing it this way simply for clarity/documentation:
public class Foo {
public void someMethod(String someArg) {
if (s == null) throw new NullPointerException("someArg cannot be null");
}
}
public class FooTest {
public void testSomeMethodNullArg() {
try {
foo.someMethod(null);
fail("someMethod failed to throw NullPointerException for null arg");
} catch (NullPointerException expected) {
// expected exception
}
}
精彩评论