I am not sure why the test case doesn't have an output of true. Both cases should give a NullPointerException.
I've tried doing this (Not exactly the same but it gives and output of 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));
}
                I believe you want to use fail here:
@Test(expected=NullPointerException.class)
public void testNullInput() {
    fail(nullString.indexOf(3));
}
Make sure to add import static org.junit.Assert.fail; if you need to.
In Java 8 and JUnit 5 (Jupiter) we can assert for exceptions as follows.
Using org.junit.jupiter.api.Assertions.assertThrows
public static < T extends Throwable > T assertThrows(Class< T > expectedType, Executable executable)
Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.
If no exception is thrown, or if an exception of a different type is thrown, this method will fail.
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);
            });
}
That approach will use the Functional Interface Executable in org.junit.jupiter.api.
Refer :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With