2014-03-25 165 views
7

我不知道为什么测试用例没有输出true。这两种情况都应该给出NullPointerExceptionJUnit测试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)); 
} 
+1

这是完全不清楚你想测试或断言这里。为什么在同一测试方法中同时存在断言和预期异常?由于'NullPointerException',断言永远不会到达。 –

回答

16

我相信你想在这里使用fail

@Test(expected=NullPointerException.class) 
public void testNullInput() { 
    fail(nullString.indexOf(3)); 
} 

确保添加import static org.junit.Assert.fail;,如果你需要。

1

在Java 8和JUnit 5(Jupiter)中,我们可以为异常声明如下。 使用org.junit.jupiter.api.Assertions.assertThrows

公共静态<Ť延伸的Throwable>ŤassertThrows(<类T> expectedType, 可执行可执行)

断言所提供的可执行的执行投expectedType并返回的一个异常例外。

如果没有抛出异常,或者抛出了不同类型的异常,则此方法将失败。

如果您不想对异常实例执行额外的检查,只需忽略返回值即可。

@Test 
public void itShouldThrowNullPointerExceptionWhenBlahBlah() { 
    assertThrows(NullPointerException.class, 
      ()->{ 
      //do whatever you want to do here 
      //ex : objectName.thisMethodShoulThrowNullPointerExceptionForNullParameter(null); 
      }); 
} 

这一方法将使用功能接口Executableorg.junit.jupiter.api

参见: