mercredi 5 juin 2019

How can I create unit test for void method with try...catch inside?

I create simple service for example:

public class MyService {

    public void process() {

        try {
            CustomerMessagesService customerMessagesService = new CustomerMessagesService();
            String message = customerMessagesService.getMessage();

            // another logic which can throw an exception                

            SpamCenterService spamCenterService = new SpamCenterService();
            spamCenterService.sendAdvertise(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This service calls from Scheduler each 1 second.

customerMessagesService return message with an advertisement text or throw an exception if this message contains illegal text. If customerMessagesService return success text - it to send to spamCenterService and if customerMessagesService throw an exception - it exception just logged. There is another logic which can throw exception between calls of these services. This exception logs too.

Now I want to create a unit test for this method. But I don't understand how to test the void method with try..catch block.

I create this:

public class MyServiceTest {

    private MyService myService;

    @Before
    public void setUp() {
        myService = new MyService();
    }

    @Test
    public void process() {
        myService.process();
    }
} 

But it is always a success because the process method doesn't throw exceptions. How can I test this method?

Aucun commentaire:

Enregistrer un commentaire