Junit expectMessage AssertionError

This is the code I want to check

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 unit 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 //exception.expectMessage?(....), it will pass.

What is going on with exception.expectMessage?

+4
source share
2 answers

The reason the test fails is caused by:

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

this code approves a message that is returned with an exception, but it is not.

Here is an example of how you could write the code and check 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);
    }
  }
}

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);
  }
}
+2
source

The usual way to test a method while waiting for an exception is to use the following annotation

@Test(expected = IllegalArgumentException.class)

where the test case fails if not thrown 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;
+1

All Articles