我不知道爲什麼測試用例沒有輸出true
。這兩種情況都應該給出NullPointerException
。JUnit測試assertEqual 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));
}
這是完全不清楚你想測試或斷言這裏。爲什麼在同一測試方法中同時存在斷言和預期異常?由於'NullPointerException',斷言永遠不會到達。 –