我不确定为什么测试用例没有输出 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));
}
最佳答案
我相信你想在这里使用fail
:
@Test(expected=NullPointerException.class)
public void testNullInput() {
fail(nullString.indexOf(3));
}
如果需要,请确保添加 import static org.junit.Assert.fail;
。
关于java - assertEqual NullPointerException 的 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22623649/