0

我正在做一个关于如何使用预期异常方法来捕获异常的教程。我对代码有 2 个问题。

  1. 我在下面显示的行中使用了单引号而不是双引号,错误消息显示“无效字符常量” 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);
    }
    }
4

1 回答 1

1

字符串

“无效年龄”在 Java 中是非法的。单引号用于单个字符。正如您所注意到的,您必须使用“无效年龄”来使 Java 对语法感到满意。

安慰

行为是正确的。JUnit 正在捕获异常,因此您在控制台上看不到它。

习俗

Java 约定是对类名使用驼峰式大小写。以大写字母开头。所以如果你的类被命名为 PersonTest 会更好。

于 2013-05-27T15:37:23.447 回答