0
我正在做一個關於如何使用Expected Exception方法來捕獲異常的教程。我有兩個問題的代碼。Junit捕獲預期的異常
我用來代替在下面示出的線雙引號單引號,該錯誤消息表示「無效字符常數」
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);
}
}
Jeanne感謝您的回覆,告訴我正確的語法,爲什麼控制檯沒有在Java中顯示錯誤消息和正確的命名約定 – user2061466