• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to test method without no return value by using JUnit.

 
jami siva
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to test method without no return value by using JUnit.

void add(int a, int b) {
int c= a + b;
}
How to test above method by using Junit in Java.
 
Junilu Lacar
Bartender
Pie
Posts: 7465
50
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, you need to find something interesting about this method. A method worth testing is a method that does something useful that can be verified from outside of the method. This code does not appear to have either of those attributes, making it pointless to unit test.
 
Marshall Blythe
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Testing a method requires you to either make assertions about a returned value or make assertions about the method's side effects (or possibly both). If a void method has no side effects (as your example illustrates) then it isn't doing anything useful and isn't worth testing. The general approach to testing void methods is to make assertions on the side effects. This often involves making assertions about the way the method interacts with collaborating classes. Mock Objects can be very useful in this case, but you need to design your classes in such a way that the mock objects can be easily substituted for the real objects at test time.
 
paul nisset
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assuming ,as other have said, that your method does something, you could output to a log file from within the test method .
You would then open the file from within the test method,read the last entry, and test that it matches what you would expect.

The main goal is to be clear on what the method is trying to achieve and test that goal .
If it's an external resource like a file,you have to mock/mimic that resource from with your test.

Use set up and tear down methods to create and remove resources that your test uses.
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jami

Further to what Junilu has said, you would never have a method like this in a project (it doesn't do anything) so asking for examples of testing it is futile.

Some good techniques have been given here for unit testing viable void methods so I hope that has been helpful to you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic