我正在做一个关于如何使用预期异常方法来捕获异常的教程。我对代码有 2 个问题。
我在下面显示的行中使用了单引号而不是双引号,错误消息显示“无效字符常量”
exception.expectMessage(containsString('invalid age'));
2.代码在Eclipse中执行正常,但是控制台页面没有在Class Person中显示消息。我应该使用关键字'extends'来扩展类personTest中的类人吗?
请告诉我为什么使用单引号会导致错误以及应该如何修改我的代码,以便在执行 testPerson 类中的代码时可以看到来自 Person 类的异常消息。谢谢!
教程代码:
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);
}
}