问你相反的问题:为什么JUnit测试方法需要不是无效的?
没有理由:因为测试方法不是为了返回客户端类将利用的结果而设计的.
单元测试的目标是验证一些断言.测试运行器调用测试方法,并且这是运行器,它解释任何断言失败或在测试执行期间抛出的任何异常以产生测试结果.
我们可能想知道为什么测试不会返回断言结果.
但这是一个坏主意,因为编写单元测试会非常麻烦:
@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之外的其他东西真的没有价值.