Search code examples
javajunitjunit4

JUnit testing for assertEqual NullPointerException


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));
}

Solution

  • 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.