Junit expectMessage 断言错误

Junit expectMessage AssertionError

这是我要测试的代码

public static Map<String, String> JSON2Map(String urlParams) {
    String [] params = urlParams.split("&");
    Map<String, String> map = new HashMap<String, String>();
    for (String param : params) {
        String[] kvs= param.split("=");
        if ( kvs.length>1)
        map.put(kvs[0], kvs[1]);
    }
    return map;
}

这是我的 junit 测试:

@Rule
public ExpectedException exception = ExpectedException.none();

@Test
public void JSON2MapTest() throws Exception {
    exception.expect(NullPointerException.class);
    exception.expectMessage("send null will occur NullPointerException");
    JSONUtils.JSON2Map(null);       
}

当我 运行 测试时它抛出:

java.lang.AssertionError: 
Expected: (exception with message a string containing "send null will occur NullPointerException" and an instance of java.lang.NullPointerException) 
got: java.lang.NullPointerException

如果我注释掉//exception.expectMessage?(....)那么它就会通过。

exception.expectMessage 怎么了?

在预期异常时测试方法的常用方法是使用以下注释

@Test(expected = IllegalArgumentException.class)

如果没有抛出 IllegalArgumentException,则测试用例失败。

编辑:org.junit.Test javadoc:

/**
 * Optionally specify <code>expected</code>, a Throwable, to cause a test method to succeed iff
 * an exception of the specified class is thrown by the method.
 */
Class<? extends Throwable> expected() default None.class;

测试失败的原因是:

exception.expectMessage("send null will occur NullPointerException");

此代码断言异常返回的消息,但存在 none。

Here 是您如何编写代码和测试预期消息的示例:

public class Person {
  private final int age;

 /**
   * Creates a person with the specified age.
   *
   * @param age the age
   * @throws IllegalArgumentException if the age is not greater than zero
   */
  public Person(int age) {
    this.age = age;
    if (age <= 0) {
      throw new IllegalArgumentException("Invalid age:" + age);
    }
  }
}

测试:

public class PersonTest {

  @Rule
  public ExpectedException exception = ExpectedException.none();

  @Test
  public void testExpectedException() {
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage(containsString("Invalid age"));
    new Person(-1);
  }
}