这是我要测试的代码

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会怎样?

最佳答案

测试失败的原因是:

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

该代码声明断言返回的消息,但没有异常。

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);
  }
}

10-05 22:43