Junit expectMessage AssertionError

时间:2015-07-01 08:09:24

标签: java junit

这是我要测试的代码

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

的情况怎么样?

2 个答案:

答案 0 :(得分:2)

测试失败的原因是:

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

答案 1 :(得分:1)

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

@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;