Java – why does the JUnit test method need to be void?
I have read many places that the test method should / must be invalid, but no one says why
I found no comments / JavaDocs in the following check in the methodvalidator
if (each.getReturnType() != Void.TYPE) { errors.add(new Exception("Method " + each.getName() + " should be void")); }
Then why should it be invalid?
Solution
Ask you the opposite question: why does the JUnit test method need to be not invalid?
We may wonder why the test does not return assertion results But this is a bad idea because writing unit tests can be cumbersome:
@Test public AssertionResult foo(){ Bar actualBar = foo.doThat(...); if (actualBar == null){ return AssertionResult.fail("actualBar == null"); } }
Writing something similar is real and readable:
@Test public void foo(){ Bar actualBar = foo.doThat(...); Assert.assertNotNull(actualBar); }
We also want to know why test methods cannot be called by other test methods, for example:
@Test public int foo(){ Bar actualBar = foo.doThat(...); //... return intValue; } @Test public void fooWithComputedInt(){ Bar actualBar = foo.doThat(foo()); //... }
But this is not a good idea, because it will couple test execution, and unit test execution must be isolated from other test execution It also enables tests to be executed multiple times, and unit tests must be executed as soon as possible
So there's really no value in having the test method return something other than void