I have a partial function as exceptionHandler
which matches the corresponding exception and throws accordingly.
I am supposed to write a test case for NoHostAvailableException
, but I am unable to throw the exception using mocking.
I have made already a mock server which makes embedded Cassandra down in Lagom.
private val handleException: PartialFunction[Throwable, Future[List[MonitoringData]]] = {
case noHostAvailableException: NoHostAvailableException => throw new CassandraNotAvailableException(TransportErrorCode
.fromHttp(Error.CassandraNotAvailableErrorCode), Error.ErrorMessageForCassandraNotAvailable)
case _ => throw new TransportException(TransportErrorCode.InternalServerError, Error.ErrorMessageForInternalServerError)
}
"not be able to interact with the database in" {
when(mockReadDAO.getData)
.thenThrow(NoHostAvailableException)
assert(thrown.isInstanceOf[NoHostAvailableException])
}
The compiler doesn't take NoHostAvailableException
as value.
Note the difference between a type
NoHostAvailableException
and a value
new NoHostAvailableException(...)
in
val e: NoHostAvailableException = new NoHostAvailableException(...)
Conceptually, this is similar to the difference between type Int
and value 42
in
val i: Int = 42
The meaning of the error
class com.datastax.driver.core.exceptions.NoHostAvailableException is not a value
is telling us we are using a type in a position where value is expected. Hence try
when(mockReadDAO.getData).thenThrow(new NoHostAvailableException(...))
instead of
when(mockReadDAO.getData).thenThrow(NoHostAvailableException)
Because NoHostAvailableException
constructor takes java.util.Map
as argument, try providing empty java.util.HashMap
like so
val emptyHashMap = new java.util.HashMap[InetSocketAddress, Throwable]()
when(mockReadDAO.getData).thenThrow(new NoHostAvailableException(emptyHashMap))