earl
earl

Reputation: 768

JUNIT test case for void method

I have a method whose JUnit test case I have to write. It just calls the main processing method of the project and does nothing else. Also, the main processing method also has return type as void.

How shall I test such a "method1"?

public void method1() {
     obj1.mainProcessingMethod():
}

Upvotes: 0

Views: 179

Answers (2)

J-J
J-J

Reputation: 5871

Inside the test you need to verify that the method mainProcessingMethod(): is called on the object obj1.

you can use something like

Mockito.verify(yourMockObject);

Upvotes: 0

user7018603
user7018603

Reputation:

Given a class:

public class A {
    private Obj obj1;

    public void method1() {
        obj1.mainProcessingMethod();
    }

    public void setObj1(Obj obj1) {
        this.obj1 = obj1;
    }
}

In test for this class, the only thing to test would be verification whether method obj1.mainProcessingMethod() was invoked exactly once.

You can achieve this with Mockito.

import org.junit.Test;
import org.mockito.Mockito;

public class ATest {
    private Obj obj1 = Mockito.mock(Obj.class);
    private A a = new A();

    @Test
    public void testMethod1() {
        a.setObj1(obj1);
        a.method1();
        Mockito.verify(obj1).mainProcessingMethod();
    }
}

Here you create a mock object for class Obj, inject it into instance of A, and later use mock object to check which method invocations it recorded.

Upvotes: 2

Related Questions