【问题标题】:Throwing Exceptions with Mockito in Kotlin在 Kotlin 中使用 Mockito 抛出异常
【发布时间】:2018-02-25 20:49:09
【问题描述】:

我正在使用 Kotlin,并试图在特定方法调用上抛出异常,但总是得到以下错误

Checked exception is invalid for this method!
Invalid: exceptions.ServiceException

这是测试

val client : IClient = Mockito.spy(Client(Cnf("https://:region.example.com", key)))


@Test(expected = ServiceException::class)
fun test400ResponseFrom() {
    val url = "https://example.com/example/user/v3/user/by-name/JACKAPPLE"

    Mockito.doThrow(ServiceException("Bad Request")).`when`(client).makeRequest(url ,riotkey)
    client.getUserDataByNameAndRegion("jackapple", "BR")
}

基本上getUserDataByNameAndRegion 方法将调用makeRequest 方法,通过这个测试,我想验证该方法是否正确处理了存根方法的结果。

原来的方法是这样的

@Throws(NotFoundException::class, ServiceException::class)
fun makeRequest(url: String, key : String) : String {
    val con = prepareConnection(url, key)
    val statusCode = con.responseCode
    when {
        (statusCode == 400) -> throw ServiceException("Bad Request")
        (statusCode == 401) -> throw ServiceException("Unauthorized")
        (statusCode == 403) -> throw ServiceException("Forbidden")
        (statusCode == 404) -> throw NotFoundException("Data not Found")
        (statusCode == 415) -> throw ServiceException("Unsupported Media Type")
        (statusCode == 429) -> throw ServiceException("Rate limit exceeded")
        (statusCode == 500) -> throw ServiceException("Internal Server Error")
        (statusCode == 502) -> throw ServiceException("Bad Gateway")
        (statusCode == 503) -> throw ServiceException("Service unavailable")
        (statusCode == 504) -> throw ServiceException("Gateway timeout")
        (statusCode == 200) -> {
            return getStringResponseFromConnection(con)
        }
        else -> {
            throw ServiceException("Respondend with Statuscode ${statusCode}")
        }
    }
}

【问题讨论】:

    标签: java testing kotlin mockito


    【解决方案1】:

    您可以尝试以下想法(取自类似的discussion on github):

    .doAnswer { throw ServiceException("Bad Request") }
    

    【讨论】:

    • 这对我有用,answer 功能似乎有效。 given(yourClass.someMethod()).willAnswer { throw ServiceException() }
    【解决方案2】:

    Kotlin 不支持creating methods that throw checked exceptions。您可以在 Java 中定义 makeRequest,也可以将 ServiceException 更改为扩展 RuntimeException。

    【讨论】:

      【解决方案3】:

      您可以使用以下内容:

      `when`(someClassMocked.muFunction).thenThrow(SocketException())
      

      【讨论】:

        【解决方案4】:

        在我的例子中,我使用了一个引发检查异常的底层 Java 客户端。我的 Kotlin 代码需要处理这些异常的一种变体,因此为了测试我能够使用的代码路径:

        whenever(someObject.doesSomething(any()).then {
            throw MyCheckedException("Error")
        }
        

        【讨论】:

          猜你喜欢
          • 2014-04-06
          • 1970-01-01
          • 2018-04-20
          • 1970-01-01
          • 1970-01-01
          • 2019-07-28
          • 2019-07-25
          • 1970-01-01
          • 2018-07-02
          相关资源
          最近更新 更多