Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues trying throw checked exception with mockito

Tags:

java

mockito

I have the below interface

public interface Interface1 {
    Object Execute(String commandToExecute) throws Exception;
}

which then I 'm trying to mock so I can test the behaviour of the class that will call it:

Interface1 interfaceMocked = mock(Interface1.class);
when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());
Interface2 objectToTest = new ClassOfInterface2(interfaceMocked);
retrievePrintersMetaData.Retrieve();

But the compiler tells me that there is an unhandled exception. The definition of the Retrieve method is:

public List<SomeClass> Retrieve() {
    try {
        interface1Object.Execute("");
    }
    catch (Exception exception) {
        return new ArrayList<SomeClass>();
    }
}

The mockito documentation only shows uses of RuntimeException, and I have not seen anything on similar on StackOverflow. I'm using Java 1.7u25 and mockito 1.9.5

like image 828
Miyamoto Akira Avatar asked Jul 06 '13 20:07

Miyamoto Akira


2 Answers

Assuming your test method doesn't declare that it throws Exception, the compiler's absolutely right. This line:

when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());

... calls Execute on an instance of Interface1. That can throw Exception, so you either need to catch it or declare that your method throws it.

I would personally recommend just declaring that the test method throws Exception. Nothing else will care about that declaration, and you really don't want to catch it.

like image 148
Jon Skeet Avatar answered Oct 12 '22 13:10

Jon Skeet


You can use doAnswer method of Mockito to thrown checked exceptions, like this

Mockito.doAnswer(
          invocation -> {
            throw new Exception("It's not bad, it's good");
          })
      .when(interfaceMocked)
      .Execute(org.mockito.ArgumentMatchers.anyString());
like image 44
Hasasn Avatar answered Oct 12 '22 13:10

Hasasn