简体   繁体   English

如何使用Scala在lagom中为NoHostAvailableException编写测试用例?

[英]How to write test case for NoHostAvailableException in lagom with Scala?

I have a partial function as exceptionHandler which matches the corresponding exception and throws accordingly.我有一个部分函数作为exceptionHandler ,它匹配相应的异常并相应地抛出。 I am supposed to write a test case for NoHostAvailableException , but I am unable to throw the exception using mocking.我应该为NoHostAvailableException编写一个测试用例,但我无法使用NoHostAvailableException抛出异常。

I have made already a mock server which makes embedded Cassandra down in Lagom.我已经制作了一个模拟服务器,它在 Lagom 中嵌入了 Cassandra。

This is the partial function.这是偏函数。

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)
}

This is the test case.这是测试用例。

"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.编译器不会将NoHostAvailableException作为值。

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从概念上讲,这类似于Int类型和值42之间的区别

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因为NoHostAvailableException构造函数将java.util.Map作为参数,尝试像这样提供空的java.util.HashMap

val emptyHashMap = new java.util.HashMap[InetSocketAddress, Throwable]() 
when(mockReadDAO.getData).thenThrow(new NoHostAvailableException(emptyHashMap))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM