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}")
}
}
}
Android App Development for Beginners All the exceptions in Kotlin are the descendants of Throwable class. In Kotlin, developers do have the privilege to create their own custom Exception. Custom Exceptions are a part of unchecked exceptions which means they will be thrown at the runtime.
Mockito has been around since the early days of Android development and eventually became the de-facto mocking library for writing unit tests. Mockito and Mockk are written in Java and Kotlin, respectively, and since Kotlin and Java are interoperable, they can exist within the same project.
Kotlin does not have checked exceptions.
You can try the following idea (taken from similar discussion on github):
.doAnswer { throw ServiceException("Bad Request") }
Kotlin does not support creating methods that throw checked exceptions. You can either define makeRequest
in Java, or change ServiceException
to extend RuntimeException
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With