简体   繁体   中英

Junit expectMessage AssertionError

This is the code I want to test

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

This is my junit test:

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

When I run the test it throws:

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

if I comment out //exception.expectMessage?(....) then it will pass.

Whats happen about the exception.expectMessage ?

The reason the test fails is because of:

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

this code is asserting the message that is returned with the exception, but there is none.

Here is an example how you could write code and test the expected message:

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

The test:

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

The usual way to test a method while expecting an Exception is to use the following annotation

@Test(expected = IllegalArgumentException.class)

where the test case fails if no IllegalArgumentException had been thrown.

Edit: 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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM