Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test void method in JUnit [duplicate]

Tags:

java

junit

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.

like image 478
Veera Avatar asked May 21 '13 06:05

Veera


People also ask

What is the purpose of the following annotation @test public void method ()?

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.


1 Answers

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 the Collection 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 a Writer. That way you can pass in a StringWriter to capture the output for testing purposes. Then you can add a method (e.g. writeToFileNamed(String filename)) to encapsulate the FileWriter creation.

like image 179
BobTheBuilder Avatar answered Oct 06 '22 10:10

BobTheBuilder