Why JUnit test methods need to be void?

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Why JUnit test methods need to be void?



I've read in lot of places that test methods should/must be void, but no one says what is the reason for this.


void



I found in MethodValidator the following check without comments/javadocs.


if (each.getReturnType() != Void.TYPE) {
errors.add(new Exception("Method " + each.getName()
+ " should be void"));
}



So why it should be void?


void





Why would a unit test be anything other than void? Returning values from a unit tests method makes no sense, so if a unit tests method returns a value, it is probably not a correct unit test or not intended as a unit test.
– Mark Rotteveel
10 mins ago






2 Answers
2



This is purely a design choice. JUnit does not know about your code, so it could not do anything if your method would return something.



So either it should discard a return value, or require you to use "void" methods. The authors chose the latter option - you coluld argue that this slightly better because it's not confusing the reader.



Note that non-@Test methods are free to do whatever they want - they don't have this limitation.





For what reason JUnit can't do anything if my method returns something? How it blocks JUnit?
– Artem Malchenko
6 mins ago





@ArtemMalchenko It doesn't block it in any way. JUnit calls your @Test methods - there is simply no convention what it should do with the value if your method returned one. Any checks for success/failure are done using assertions (i.e. throwables) - you could say this is "the only result JUnit cares about" (eventhough it's not really a "return").
– jurez
3 mins ago




@Test



Ask you the reverse question : Why JUnit test methods would need to be not void ?
No reason : because a test method is not designed to return a result that will be exploited by a client class.
The goal of an unit test is to validate some assertions. A test runner invokes the test methods and and this is the runner that interprets any assertion failure or any exception thrown during the test execution to produce the test result.
So the test method needs to return nothing.


void






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Vi,w64leTX,wCiL5sWJk8eIc,uFmKYaK11H 6AxeYDIJXx
AD,tjtkkbkfUH0I NYqBy1yTKJFK8 C 9ovoY1,RFpO5AUYTSMniBsJS1vWirgVLIKBc6Y,OCajZ44DuuGKtdO6aHtUE82

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results