dimanche 25 février 2018

Throwing Exceptions with Mockito in Kotlin

I am using Kotlin and am trying to throw an Exception on a specific method invocation but always get the following error

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

This is the test

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

Basically the getUserDataByNameAndRegion method will invoke the makeRequest method and with this test I want to validate that the method is handling the result of the stubbed method correctly.

The original method looks like this

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

Aucun commentaire:

Enregistrer un commentaire