Manu Chadha
Manu Chadha

Reputation: 16723

Checked exception is invalid for this method Error

As far as I know, Scala doesn't have checked exceptions i.e. I don't need to specify the exception a method will throw.

I have a method A of class a under test. It calls method B of class b. I want to test behavior when B throws an exception.

class b{
    def B()={...}
}

I have mocked B

when(mockB.B).thenThrow(new UserDoesNotExistException("exception"))

When I do this, I get error Checked exception is invalid for this method!

This answers explains w.r.t. Java - throw checked Exceptions from mocks with Mockito

While changing UserDoesNotExistException to RuntimeException works for me, I am curious to know if it is possible for me to test by throwing UserDoesNotExistException

In my logic, A has different paths depending on which type of exception is thrown, thus I need to throw specific exceptions from my tests rather than throwing generic RuntimeException.

Upvotes: 2

Views: 1710

Answers (2)

Manu Chadha
Manu Chadha

Reputation: 16723

thenAnswer also worked -

when(mockB.B).thenAnswer(invocation=>throw new UserDoesNotExistException("exception"))

Upvotes: 2

Tomer Shetah
Tomer Shetah

Reputation: 8529

The short answer is yes you can. How can you do that? You need to add the throws annotation to the B method:

class b{
    @throws(classOf[UserDoesNotExistException])
    def B()={...}
}

According to the Scala Cookbook regarding throws annotation:

First, whether the consumers are using Scala or Java, if they’re writing robust code, they’ll want to know that something failed. Second, if they’re using Java, the @throws annotation is the Scala way of providing the throws method signature to Java consumers.

Since Mockito.java is written in java, it has to know which user exceptions can be thrown. RuntimeException, should not be written explicitly, as it can always be thrown.

Another possible solution, is upgrading to the latest mockito-scala (version 1.15.0 at the moment), you can use:

org.mockito.MockitoSugar.when

which is pure scala, and then the following code should work:

import org.mockito.MockitoSugar.{mock, when}
val bMock = mock[b]
when(bMock.B()).thenThrow(new UserDoesNotExistException("exception"))

Upvotes: 1

Related Questions