Question

I am doing a tutorial on how to use Expected Exception method to catch exception. I have 2 questions for the code.

  1. I used single quote instead of double quote in the line shown below, the error message says 'Invalid character constant' exception.expectMessage(containsString('invalid age'));

    2.The code executed fine in the Eclipse, but the console page doesn't show message in Class Person. Should I use keyword 'extends' to extend Class Person inside the class personTest?

    Please advise me why using single quote cause the error and how should modify my code so I can see the exception message from Person Class when execute the code in testPerson class. Thanks!

Tutorial code:

public class Person {
private final String name;
private final int age;
public  Person(String name, int age){
    this.name =name;
    this.age = age;
    if (age <= 0){
        throw new IllegalArgumentException("Invalid age: " + age);
    }
}

}

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
import org.junit.Test;

public class personTest {
    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Test
    public void testExpectedException(){
    exception.expect(IllegalArgumentException.class);
    //exception.expectMessage(containsString('invalid age'));
    exception.expectMessage(containsString("Invalid age"));

    new Person("Joe", -1);
    }
    }
Was it helpful?

Solution

Strings

'invalid age' is illegal in Java. Single quotes are used for a single character. As you note,d you have to use "invalid age" to make Java happy regarding syntax.

Console

The behavior is correct. JUnit is catching the exception so you don't see it on the console.

Convention

Java convention is to use camel case for classnames. Beginning with an uppercase letter. So it would be better if your class was named PersonTest.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top