How to test void method using JUnit.
void add(int a, int b) {
int c= a + b;
}
How to test above method by using Junit in Java.
The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method. Any exceptions thrown by the test will be reported by JUnit as a failure.
If a method has side effects, you can check them in your JUnit test.
In your example, the method has no side effects, so there is nothing to test.
If you still want to test it, you can use reflection to do so, but I don't think it is good practice.
You can check JUnit FAQ related section:
How do I test a method that doesn't return anything?
Often if a method doesn't return a value, it will have some side effect. Actually, if it doesn't return a value AND doesn't have a side effect, it isn't doing anything.
There may be a way to verify that the side effect actually occurred as expected. For example, consider the
add()
method in theCollection
classes. There are ways of verifying that the side effect happened (i.e. the object was added). You can check the size and assert that it is what is expected:@Test public void testCollectionAdd() { Collection collection = new ArrayList(); assertEquals(0, collection.size()); collection.add("itemA"); assertEquals(1, collection.size()); collection.add("itemB"); assertEquals(2, collection.size()); }
Another approach is to make use of MockObjects.
A related issue is to design for testing. For example, if you have a method that is meant to output to a file, don't pass in a filename, or even a
FileWriter
. Instead, pass in aWriter
. That way you can pass in aStringWriter
to capture the output for testing purposes. Then you can add a method (e.g.writeToFileNamed(String filename)
) to encapsulate theFileWriter
creation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With