方法前提条件是否应进行单元测试?

Ada*_*ion 4 java junit unit-testing guava

我使用Guava的前置条件来验证我的方法的输入,例如:

class TestedClass {
  public double sqrt(double value) {
    Preconditions.checkArgument(value >= 0.0, "negative value: %s", value);
  }
}
Run Code Online (Sandbox Code Playgroud)

我想知道前提条件是否应进行单元测试?我应该测试一下:

@Rule
public ExpectedException exception = ExpectedException.none();

@Test
public void shouldFailWhenValueIsNegative() {
   exception.thown(IllegalArgumentException.class);
   exception.expectMessage("negative value: -1");

   new TestedClass().sqrt(-1);
} 
Run Code Online (Sandbox Code Playgroud)

Col*_*inD 5

我的意见是,您通常应该使用测试来验证方法的行为是否与其合同(包括前置条件)指定的行为相匹配.如果你说你的方法在给出参数的负值时抛出某个异常,那么进行一次测试以确保它是真的.

对于非常常见的事情,例如NullPointerException,guava-testlibhas NullPointerTester,我们用于测试,这些测试NPE是针对未注释的参数抛出的@Nullable.