1

I am trying to test a void method in service class using junit. I am not really sure how to test it.

Code:

public class Service{
private static final Logger LOGGER = LogManager.getLogger(Service.class);

    private final ServiceDAO serviceDAO;
    private final RtyDAO rtyDAO;

    public Service(ServiceDAO serviceDAO,
            RtyDAO rtyDAO) {
        this.serviceDAO = serviceDAO;
        this.rtyDAO = rtyDAO;
    }

    public void voidMethod(JSONObject object) {
        try {
            Rty rty = serviceDAO.getSomething();
            String output = rtyDAO.persist(rty);
            if("TRUE".equalsIgnoreCase(output)){
               LOGGER.info("Success"):
            }else{
               LOGGER.info("Failure"):
            }
        }
}

As the above method is void i am not sure how to test this. I am trying like below:

public class ServiceTest {

@InjectMocks
Service service;

@Mock 
RtyDAO RtyDAO;

@Mock
Rty rty;

@Mock
ServiceDAO serviceDAO;



@Test
public void testVoid(){
   Mockito.when(serviceDAO.getSomething()).thenReturn(rty);
Mockito.when(rtyDAO.persist(rty)).thenReturn("Success");
//how to test result here if the persisting happened without any issues?
    }
ging
  • 219
  • 7
  • 20

1 Answers1

0

As you said, the method is Void, so its hard to test. But there is a way! You could use Mockito to certify that both calls were done correctly. Check this answer: Mockito : how to verify method was called on an object created within a method?

Bruno
  • 2,889
  • 1
  • 18
  • 25
  • Thanks for your reply. But i am having hard time understanding verify. What does it do? whats the difference between doNothing() and Verify() – ging Sep 13 '18 at 03:17
  • The verify method will just verify that the method on the mocked object got called. Its just that. You can pass a value to it to verify that it was called N times – Bruno Sep 13 '18 at 15:15