JUnit test methods can't return a value

Gerardo Cauich :

Why JUnit test methods can't return a value?

Documentation says (emphasis mine):

Test methods and lifecycle methods may be declared locally within the current test class, inherited from superclasses, or inherited from interfaces (see Test Interfaces and Default Methods). In addition, test methods and lifecycle methods must not be abstract and must not return a value.

Why is it enforced like this?

Is this purely a design choice? Is it a best practice?

davidxxx :

Is this purely a design choice?

Yes. In theory, nothing prevents the Junit runner (component thats runs tests of a test class) from accepting as valid a test method with a return value.

Is it a best practice?

Indeed. More you restrict the ways of specifying a unit test method, more you ensure that no misuse happens.

For example look at that simple example that would suppose a test method to return a value.
A addFoo() test method that asserts that the method does what it is expected and that also returns the Foo fixture created :

@Test
public Foo addFoo(){
   Foo foo = new Foo(...);

   // call the api ...
   sut.addFoo(foo); 

   // assertion
   assertEquals(...);

   // return the foo fixture
   return foo;
}

And here a addFooBar() test method that retrieves the Foo fixture created by the previous method and then asserts that the method addFooBar() does what it is expected :

@Test
public void addFooBar(){
   Foo foo = addFoo();
   Bar bar = new Bar(..., foo);

   // call the api ...
   sut.addFooBar(bar); 

   // assertion
   assertEquals(...);
}

That lays multiple issues :

  • Does the method addFoo() should be executed multiple times ? It may hurt the test speed execution and make test reports unclear.
  • The addFoo() test result may make the addFooBar() test result to fail in spit of a correct implementation.
    How to diagnostic the issue origin ? We added useless complexity.
  • The addFoo() test result may make the addFooBar() test result to succeed in spit of a incorrect implementation. Indeed, an incorrect implementation in addFoo() may compensate an incorrect implementation in addFooBar()

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=418436&siteId=1