java - JUnit testing for assertEqual NullPointerException -
i not sure why test case doesn't have output of true. both cases should give nullpointerexception.
i've tried doing (not same gives , 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); (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; } (int = index; < 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 want use fail here:
@test(expected=nullpointerexception.class) public void testnullinput() { fail(nullstring.indexof(3)); } make sure add import static org.junit.assert.fail; if need to.
Comments
Post a Comment