如何以正确的方式为 JUnit 测试构造函数?

How to test a constructor in a proper way for JUnit?

我目前正在为某些代码编写 Junit 测试套件。

我做的是,有一个class叫做Person,它的构造函数中有name、height、weight变量。

在其构造函数中,如果名称的字符数超过 20,则会抛出异常。

如果测试需要测试构造函数不接受超过20个字符的名称,我应该如何编写测试方法?

例如,如果我写:

@Test (expected = IllegalArgumentException.class)
public void testPersoin() {
Person person = new Person("BobBobBobBobBobBobBobBobBobBobBobBobBobBobBobBobBobBob", "172", "62");
}

当我 运行 它时,它会通过测试用例,但它只测试名称的长度: “BobBobBobBobBobBobBobBobBobBobBobBobBobBobBobBobBobBob”,但不是任何更长或更短的名称。

有没有正确的方法来测试名称字符是否超过20? 我应该在测试方法中写 if/else 条件吗?我应该如何在测试套件中演示 if 的边界?

谢谢!

有什么问题:

if(name==null || name.length()>20)
  throw new IllegalArgumentException();
...//rest of code in constructor

我不确定你需要什么,但也许这就是你想要的:

@Test (expected = IllegalArgumentException.class)
public void testPersoin() {
    // Extract the name
    String name = "BobBobBobBobBobBobBobBobBobBobBobBobBobBobBobBobBobBob";
    // Assert that it is over 20 characters long
    assertTrue(name.length() > 20);
    person = new Person(name, "172", "62");
}

有时您可能还需要在测试前断言测试参数有效。但这不是最好的方法。更好的做法是让测试尽可能清晰,处理所有案例并正确命名案例,例如:

private static final String NAME_10 = "0123456789"; // below 20
private static final String NAME_20 = NAME_10 + NAME_10; // exactly 20
private static final String NAME_21 = NAME_20 + "x"; // over 20

private Person person;

@Test(expected = IllegalArgumentException.class)
public void personNameOver20Throws() {
    new Person(NAME_21, "172", "62");
}

// I assume that null and empty names are not allowed either
@Test(expected = IllegalArgumentException.class)
public void personNameNullThrows() {
    new Person(null, "172", "62");
}

@Test(expected = IllegalArgumentException.class)
public void personNameEmptyThrows() {
    person = new Person("", "172", "62");
}

@Test
public void personNameBelow20Works() {
    person = new Person(NAME_10, "172", "62");
}

@Test
public void personNameExactly20Works() {
    person = new Person(NAME_10, "172", "62");
}