JUnit check for assertEqual NullPointerException

I am not sure why the test case has no true output. Both cases should give a NullPointerException .

I tried to do this (not quite the same thing, but it gives and outputs true ):

  String nullStr = null; //@Test public int NullOutput1() { nullStr.indexOf(3); return 0; } //@Test(expected=NullPointerException.class) public int NullOutput2() { nullStr.indexOf(2); return 0; } @Test(expected=NullPointerException.class) public void testboth() { assertEquals(NullOutput1(), NullOutput2()); } 

Runner:

 import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunnerStringMethods { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunitMyIndexOf.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } 

Method:

 public static int myIndexOf(char[] str, int ch, int index) { if (str == null) { throw new NullPointerException(); } // increase efficiency if (str.length <= index || index < 0) { return -1; } for (int i = index; i < str.length; i++) { if (index == str[i]) { return i; } } // if not found return -1; } 

Test case:

 @Test(expected=NullPointerException.class) public void testNullInput() { assertEquals(nullString.indexOf(3), StringMethods.myIndexOf(null, 'd',3)); } 
+8
java junit junit4
source share
2 answers

I believe you want to use fail here:

 @Test(expected=NullPointerException.class) public void testNullInput() { fail(nullString.indexOf(3)); } 

Be sure to add import static org.junit.Assert.fail; , if you need.

+16
source share

In Java 8 and JUnit 5 (Jupiter) we can claim for exceptions as follows. Using org.junit.jupiter.api.Assertions.assertThrows

public static <T extends Throwable> T assertThrows (class <T> expectedType, Executable executable)

Claims that executing the provided executable throws an exception from the expected type and returns an exception.

If an exception is not thrown, or if an exception of a different type is thrown, this method will not be executed.

If you do not want to perform additional checks on the exception instance, simply ignore the return value.

 @Test public void itShouldThrowNullPointerExceptionWhenBlahBlah() { assertThrows(NullPointerException.class, ()->{ //do whatever you want to do here //ex : objectName.thisMethodShoulThrowNullPointerExceptionForNullParameter(null); }); } 

This approach will use the org.junit.jupiter.api functional interface in org.junit.jupiter.api .

Contact:

+1
source share

All Articles