JUnit testing for assertEqual NullPointerException
我不确定为什么测试用例没有的输出。这两种情况都应该给出一个 .true
NullPointerException
我尝试过这样做(不完全相同,但它给出了和输出):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());
}
跑步者:
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());
}
}
方法:
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(expected=NullPointerException.class)
public void testNullInput() {
assertEquals(nullString.indexOf(3), StringMethods.myIndexOf(null, 'd',3));
}