我在很多地方读到测试方法应该/必须是void
,但没有人说这样做的原因。
我在MethodValidator中发现了以下检查,没有注释/ javadocs。
if (each.getReturnType() != Void.TYPE) {
errors.add(new Exception("Method " + each.getName()
+ " should be void"));
}
那么为什么它应该是
void
?我在很多地方读到测试方法应该/必须是void
,但没有人说这样做的原因。
我在MethodValidator中发现了以下检查,没有注释/ javadocs。
if (each.getReturnType() != Void.TYPE) {
errors.add(new Exception("Method " + each.getName()
+ " should be void"));
}
void
?@Test
public AssertionResult foo(){
Bar actualBar = foo.doThat(...);
if (actualBar == null){
return AssertionResult.fail("actualBar == null");
}
}
请编写易于阅读且简明易懂的内容:
@Test
public void foo(){
Bar actualBar = foo.doThat(...);
Assert.assertNotNull(actualBar);
}
@Test
public int foo(){
Bar actualBar = foo.doThat(...);
//...
return intValue;
}
@Test
public void fooWithComputedInt(){
Bar actualBar = foo.doThat(foo());
//...
}
但这也不是一个好主意,因为这会使测试执行与单元测试执行耦合在一起,而单元测试必须与其他测试隔离开来。同时,这也将导致测试被多次执行,而单元测试必须尽可能快地执行。
因此,除了void
之外,让测试方法返回其他内容真的没有任何价值。
@Test
方法 - 只是没有约定如果您的方法返回一个值应该做什么。任何成功/失败的检查都使用断言(即可抛出的异常)完成 - 您可以说这是 "JUnit 关心的唯一结果"(尽管它实际上不是一个 "返回")。 - jurez