Expected Exception 메서드를 사용하여 예외를 catch하는 방법에 대한 자습서를 작성하고 있습니다. 코드에 대해 2 가지 질문이 있습니다. 내가 대신 아래 라인에 큰 따옴표의 작은 따옴표를 사용Junit catch 예상 예외
는 오류 메시지가
exception.expectMessage(containsString('invalid age'));
2. 코드가 이클립스에서 잘 실행 '잘못된 문자 상수', 그러나 말한다 콘솔 페이지에 클래스 Person에 메시지가 표시되지 않습니다. personTest 클래스 내에서 Class Person을 확장하기 위해 'extends'키워드를 사용해야합니까?
작은 따옴표를 사용하면 오류가 발생하고 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