Best Fuel code snippet using com.github.kittinunf.fuel.private.failure
MessageHandler.kt
Source:MessageHandler.kt
1package matterlink.api2import com.github.kittinunf.fuel.core.FuelManager3import com.github.kittinunf.fuel.core.Method4import com.github.kittinunf.fuel.core.ResponseDeserializable5import com.github.kittinunf.fuel.core.extensions.cUrlString6import com.github.kittinunf.fuel.core.extensions.jsonBody7import com.github.kittinunf.fuel.coroutines.awaitStringResponseResult8import com.github.kittinunf.fuel.httpGet9import com.github.kittinunf.fuel.httpPost10import com.github.kittinunf.result.Result11import kotlinx.coroutines.CoroutineName12import kotlinx.coroutines.CoroutineScope13import kotlinx.coroutines.Dispatchers14import kotlinx.coroutines.ExperimentalCoroutinesApi15import kotlinx.coroutines.Job16import kotlinx.coroutines.ObsoleteCoroutinesApi17import kotlinx.coroutines.channels.BroadcastChannel18import kotlinx.coroutines.channels.Channel19import kotlinx.coroutines.channels.SendChannel20import kotlinx.coroutines.channels.actor21import kotlinx.coroutines.channels.broadcast22import kotlinx.coroutines.channels.consumeEach23import kotlinx.coroutines.delay24import kotlinx.coroutines.isActive25import kotlinx.coroutines.launch26import kotlinx.coroutines.runBlocking27import kotlinx.serialization.json.JSON28import kotlinx.serialization.list29import matterlink.Logger30import java.io.Reader31import java.net.ConnectException32import kotlin.coroutines.CoroutineContext33/**34 * Created by nikky on 07/05/18.35 *36 * @author Nikky37 * @version 1.038 */39open class MessageHandler : CoroutineScope {40 override val coroutineContext: CoroutineContext = Job()41 private var enabled = false42 private var connectErrors = 043 private var reconnectCooldown = 0L44 private var sendErrors = 045 private var sendChannel: SendChannel<ApiMessage> = senderActor()46 private val messageStream = Channel<ApiMessage>(Channel.UNLIMITED)47 @UseExperimental(ExperimentalCoroutinesApi::class)48 var broadcast: BroadcastChannel<ApiMessage> = broadcast {49 while (true) {50 val msg = messageStream.receive()51 send(msg)52 }53 }54 private set55 private val keepOpenManager = FuelManager().apply {56 timeoutInMillisecond = 057 timeoutReadInMillisecond = 058 }59 var config: Config = Config()60 var logger = object : Logger {61 override fun info(message: String) = println("INFO: $message")62 override fun debug(message: String) = println("DEBUG: $message")63 override fun error(message: String) = println("ERROR: $message")64 override fun warn(message: String) = println("WARN: $message")65 override fun trace(message: String) = println("TRACE: $message")66 }67 suspend fun stop(message: String? = null) {68 if (message != null && config.announceDisconnect) {69 sendStatusUpdate(message)70 }71 enabled = false72 rcvJob?.cancel()73 rcvJob = null74 }75 private var rcvJob: Job? = null76 suspend fun start(message: String?, clear: Boolean) {77 logger.debug("starting connection")78 if (clear) {79 clear()80 }81 enabled = true82 rcvJob = messageBroadcast()83 if (message != null && config.announceConnect) {84 sendStatusUpdate(message)85 }86 }87 private suspend fun clear() {88 val url = "${config.url}/api/messages"89 val (request, response, result) = url.httpGet()90 .apply {91 if (config.token.isNotEmpty()) {92 headers["Authorization"] = "Bearer ${config.token}"93 }94 }95 .awaitStringResponseResult()96 when (result) {97 is Result.Success -> {98 val messages: List<ApiMessage> = JSON.nonstrict.parse(ApiMessage.list, result.value)99 messages.forEach { msg ->100 logger.trace("skipping $msg")101 }102 logger.debug("skipped ${messages.count()} messages")103 }104 is Result.Failure -> {105 logger.error("failed to clear messages")106 logger.error("url: $url")107 logger.error("cUrl: ${request.cUrlString()}")108 logger.error("response: $response")109 logger.error(result.error.exception.localizedMessage)110 result.error.exception.printStackTrace()111 }112 }113 }114 open suspend fun sendStatusUpdate(message: String) {115 transmit(ApiMessage(text = message))116 }117 open suspend fun transmit(msg: ApiMessage) {118// if (streamConnection.isConnected || streamConnection.isConnecting) {119 if (msg.username.isEmpty())120 msg.username = config.systemUser121 if (msg.gateway.isEmpty()) {122 logger.error("missing gateway on message: $msg")123 return124 }125 logger.debug("Transmitting: $msg")126 sendChannel.send(msg)127// }128 }129 @Deprecated("use coroutine api", level = DeprecationLevel.ERROR)130 fun checkConnection() {131 }132 @UseExperimental(ObsoleteCoroutinesApi::class)133 private fun CoroutineScope.senderActor() = actor<ApiMessage>(context = Dispatchers.IO) {134 consumeEach {135 try {136 logger.debug("sending $it")137 val url = "${config.url}/api/message"138 val (request, response, result) = url.httpPost()139 .apply {140 if (config.token.isNotEmpty()) {141 headers["Authorization"] = "Bearer ${config.token}"142 }143 }144 .jsonBody(it.encode())145 .responseString()146 when (result) {147 is Result.Success -> {148 logger.debug("sent $it")149 sendErrors = 0150 }151 is Result.Failure -> {152 sendErrors++153 logger.error("failed to deliver: $it")154 logger.error("url: $url")155 logger.error("cUrl: ${request.cUrlString()}")156 logger.error("response: $response")157 logger.error(result.error.exception.localizedMessage)158 result.error.exception.printStackTrace()159// close()160 throw result.error.exception161 }162 }163 } catch (connectError: ConnectException) {164 connectError.printStackTrace()165 sendErrors++166 }167 }168 }169 private fun CoroutineScope.messageBroadcast() = launch(context = Dispatchers.IO + CoroutineName("msgBroadcaster")) {170 loop@ while (isActive) {171 logger.info("opening connection")172 val url = "${config.url}/api/stream"173 val (request, response, result) = keepOpenManager.request(Method.GET, url)174 .apply {175 if (config.token.isNotEmpty()) {176 headers["Authorization"] = "Bearer ${config.token}"177 }178 }179 .responseObject(object : ResponseDeserializable<Unit> {180 override fun deserialize(reader: Reader) =181 runBlocking(Dispatchers.IO + CoroutineName("msgReceiver")) {182 logger.info("connected successfully")183 connectErrors = 0184 reconnectCooldown = 0185 reader.useLines { lines ->186 lines.forEach { line ->187 val msg = ApiMessage.decode(line)188 logger.debug("received: $msg")189 if (msg.event != "api_connect") {190 messageStream.send(msg)191 }192 }193 }194 }195 })196 when (result) {197 is Result.Success -> {198 logger.info("connection closed")199 }200 is Result.Failure -> {201 connectErrors++202 reconnectCooldown = connectErrors * 1000L203 logger.error("connectErrors: $connectErrors")204 logger.error("connection error")205 logger.error("curl: ${request.cUrlString()}")206 logger.error(result.error.localizedMessage)207 result.error.exception.printStackTrace()208 if (connectErrors >= 10) {209 logger.error("Caught too many errors, closing bridge")210 stop("Interrupting connection to matterbridge API due to accumulated connection errors")211 break@loop212 }213 }214 }215 delay(reconnectCooldown) // reconnect delay in ms216 }217 }218}...
MojangKt.kt
Source:MojangKt.kt
1package dev.dewy.mojangkt2import com.github.kittinunf.fuel.core.FuelManager3import com.github.kittinunf.fuel.gson.jsonBody4import com.github.kittinunf.fuel.gson.responseObject5import com.github.kittinunf.fuel.httpDelete6import com.github.kittinunf.fuel.httpGet7import com.github.kittinunf.fuel.httpPost8import com.github.kittinunf.fuel.httpPut9import com.github.kittinunf.result.Result10import com.google.gson.Gson11import com.google.gson.JsonObject12import java.util.Base6413import java.util.UUID14import java.util.regex.Pattern15import kotlin.coroutines.resume16import kotlin.coroutines.resumeWithException17import kotlin.coroutines.suspendCoroutine18class MojangKt {19 private val gson = Gson()20 @Suppress("UNUSED")21 var token = ""22 set(value) {23 field = value24 if (value.isEmpty()) {25 FuelManager.instance.baseHeaders = emptyMap()26 return27 }28 FuelManager.instance.baseHeaders = mapOf(29 "Authorization" to "Bearer $value"30 )31 }32 suspend fun getPlayerFromName(name: String): PrimitivePlayer = suspendCoroutine { cont ->33 "https://api.mojang.com/users/profiles/minecraft/$name"34 .httpGet()35 .responseObject<PrimitivePlayer> { _, _, result ->36 when (result) {37 is Result.Failure -> {38 cont.resumeWithException(result.getException())39 }40 is Result.Success -> {41 cont.resume(result.value)42 }43 }44 }45 }46 suspend fun getPlayersFromNames(names: List<String>): List<PrimitivePlayer> = suspendCoroutine { cont ->47 "https://api.mojang.com/profiles/minecraft"48 .httpPost()49 .jsonBody(50 names, gson51 )52 .responseObject<List<PrimitivePlayer>> { _, _, result ->53 when (result) {54 is Result.Failure -> {55 cont.resumeWithException(result.getException())56 }57 is Result.Success -> {58 cont.resume(result.value)59 }60 }61 }62 }63 suspend fun getProfileFromUuid(uuid: String): Profile = suspendCoroutine { cont ->64 "https://sessionserver.mojang.com/session/minecraft/profile/$uuid"65 .httpGet()66 .responseString {_, _, result ->67 when (result) {68 is Result.Failure -> {69 cont.resumeWithException(result.getException())70 }71 is Result.Success -> {72 val obj = gson.fromJson(result.value, JsonObject::class.java)73 val encodedProperties = obj["properties"].asJsonArray[0].asJsonObject["value"].asString74 val id = obj["id"].asString75 val name = obj["name"].asString76 val legacy = obj.has("legacy")77 var skinUrl = ""78 var skinType = getSkinType(id)79 var capeUrl = ""80 if (encodedProperties != null) {81 val texturesObj = gson.fromJson(String(Base64.getDecoder()82 .decode(encodedProperties)), JsonObject::class.java)83 .getAsJsonObject("textures")84 val skinObj = texturesObj.getAsJsonObject("SKIN")85 val capeObj = texturesObj.getAsJsonObject("CAPE")86 if (skinObj != null) {87 skinUrl = skinObj["url"].asString88 skinType = if (skinObj.has("metadata")) SkinType.SLIM else SkinType.DEFAULT89 }90 if (capeObj != null) {91 capeUrl = capeObj["url"].asString92 }93 }94 cont.resume(Profile(PrimitivePlayer(id, name, legacy), Skin(skinUrl, skinType), capeUrl))95 }96 }97 }98 }99 suspend fun getNameHistory(uuid: String): NameHistory = suspendCoroutine { cont ->100 "https://api.mojang.com/user/profiles/$uuid/names"101 .httpGet()102 .responseObject<List<NameHistoryNode>> { _, _, result ->103 when (result) {104 is Result.Failure -> {105 cont.resumeWithException(result.getException())106 }107 is Result.Success -> {108 cont.resume(NameHistory(result.value))109 }110 }111 }112 }113 suspend fun changeName(name: String) = suspendCoroutine<Unit> { cont ->114 "https://api.minecraftservices.com/minecraft/profile/name/$name"115 .httpPut()116 .response { _, response, result ->117 when (result) {118 is Result.Failure -> {119 when (response.statusCode) {120 400 -> cont.resumeWithException(InvalidNameException("Name must follow Mojang's name rules."))121 401 -> cont.resumeWithException(UnauthorizedAccessException("Token expired or incorrect."))122 403 -> cont.resumeWithException(UnavailableNameException("Name either taken or is in some other way unavailable."))123 500 -> cont.resumeWithException(TimedOutException("Timed out."))124 }125 }126 is Result.Success -> {127 cont.resume(Unit)128 }129 }130 }131 }132 suspend fun resetSkin(uuid: String) = suspendCoroutine<Unit> { cont ->133 "https://api.mojang.com/user/profile/$uuid/skin"134 .httpDelete()135 .responseString { _, _, result ->136 when (result) {137 is Result.Failure -> {138 cont.resumeWithException(result.getException())139 }140 is Result.Success -> {141 val errorObj = gson.fromJson(result.value, JsonObject::class.java)142 if (errorObj != null)143 cont.resumeWithException(MojangApiException("${errorObj["error"].asString}: ${errorObj["errorMessage"].asString}"))144 else145 cont.resume(Unit)146 }147 }148 }149 }150 suspend fun getBlockedServers(): List<String> = suspendCoroutine { cont ->151 "https://sessionserver.mojang.com/blockedservers"152 .httpGet()153 .responseString { _, _, result ->154 when (result) {155 is Result.Failure -> {156 cont.resumeWithException(result.getException())157 }158 is Result.Success -> {159 cont.resume(result.value.split("\n"))160 }161 }162 }163 }164 @Suppress("NAME_SHADOWING")165 private fun getSkinType(uuid: String): SkinType {166 val uuid = UUID.fromString(Pattern.compile("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})")167 .matcher(uuid.replace("-", "")).replaceAll("$1-$2-$3-$4-$5"))168 return if ((uuid.hashCode() and 1) != 0)169 SkinType.SLIM170 else171 SkinType.DEFAULT172 }173}...
FuelWebService.kt
Source:FuelWebService.kt
...33 FuelManager.instance.timeoutReadInMillisecond = TimeUnit.SECONDS.toMillis(15).toInt()34 }35 inline fun <reified T: Any> get(url: String,36 crossinline success: (Request, Response, T) -> Unit,37 noinline failure: ((Request, Response, Exception) -> Unit)? = null38 ): Request = request<T>(Fuel.get(url), success, failure)39 inline fun <reified T: Any> head(url: String,40 crossinline success: (Request, Response, T) -> Unit,41 noinline failure: ((Request, Response, Exception) -> Unit)? = null42 ): Request = request<T>(Fuel.head(url), success, failure)43 inline fun <reified T: Any> post(url: String,44 crossinline success: (Request, Response, T) -> Unit,45 noinline failure: ((Request, Response, Exception) -> Unit)? = null46 ): Request = request<T>(Fuel.post(url), success, failure)47 inline fun <reified T: Any> put(url: String,48 crossinline success: (Request, Response, T) -> Unit,49 noinline failure: ((Request, Response, Exception) -> Unit)? = null50 ): Request = request<T>(Fuel.put(url), success, failure)51 inline fun <reified T: Any> delete(url: String,52 crossinline success: (Request, Response, T) -> Unit,53 noinline failure: ((Request, Response, Exception) -> Unit)? = null54 ): Request = request<T>(Fuel.delete(url), success, failure)55 @Deprecated("@hide")56 inline fun <reified T: Any> request(request: Request,57 crossinline success: (Request, Response, T) -> Unit,58 noinline failure: ((Request, Response, Exception) -> Unit)? = null59 ): Request = request.responseObject(Deserializer(gson, T::class)) { _, response, result: Result<T, FuelError> ->60 result.fold({ data ->61 success(request, response, data)62 }, { fuelError ->63 Logger.error("${fuelError.response.statusCode} ${fuelError.response.url}", fuelError.exception)64 failure?.invoke(request, response, fuelError.exception)65 })66 }67 inline fun <reified T: Any> deserialize(content: String): T? =68 Deserializer(gson, T::class).deserialize(content)69 inner class Deserializer<T: Any>(private val gson: Gson, private val klass: KClass<T>): ResponseDeserializable<T> {70 override fun deserialize(content: String): T? {71 try {72 return gson.fromJson(content, klass.java)73 } catch (e: JsonSyntaxException) {74 Logger.wtf(e)75 return null76 }77 }78 }...
TmdbUtilImpl.kt
Source:TmdbUtilImpl.kt
1package ash.kotlin.graphql.data2import ash.kotlin.graphql.AppConfig3import ash.kotlin.graphql.TmdbGqlException4import ash.kotlin.graphql.types.genre.GenreType5import ash.kotlin.graphql.types.keyword.KeywordType6import ash.kotlin.graphql.types.movie.MovieType7import ash.kotlin.graphql.types.multisearch.PersonType8import ash.kotlin.graphql.types.multisearch.TvShowType9import ash.kotlin.graphql.types.tvseason.TvSeasonType10import com.github.kittinunf.fuel.core.FuelManager11import com.github.kittinunf.fuel.core.ResponseDeserializable12import com.github.kittinunf.fuel.gson.responseObject13import com.github.kittinunf.fuel.httpGet14import com.github.kittinunf.result.Result15import com.google.gson.Gson16import com.google.gson.JsonParser17import org.jvnet.hk2.annotations.Service18import javax.inject.Inject19class TmdbUtilImpl @Inject constructor(config: AppConfig) : TmdbUtil20{21 init22 {23 FuelManager.instance.basePath = config.baseUrl24 }25 override fun getGenreList(): List<GenreType>26 {27 return sendListRequest("/genre/movie/list")28 }29 override fun getMovieKeywords(movieId: Int): List<KeywordType>30 {31 return sendListRequest("/movie/$movieId/keywords")32 }33 override fun getTvSeason(tvShowId: Int, seasonNumber: Int): TvSeasonType34 {35 return sendRequest("/tv/$tvShowId/season/$seasonNumber") ?: TvSeasonType()36 }37 override fun searchMoviesWithQuery(query: String): List<MovieType>38 {39 return sendListRequest("/search/movie", listOf(query to "query"))40 }41 override fun searchMoviesWithMultipleParameters(params: List<Pair<String, Any?>>): List<MovieType>42 {43 return sendListRequest("/search/movie", params)44 }45 override fun searchMulti(params: List<Pair<String, Any?>>): List<Any>46 {47 var data = emptyList<Any>()48 "/search/multi".httpGet(params).responseObject(MultiDeserializer()) { _, _, result ->49 when (result)50 {51 is Result.Failure -> throw TmdbGqlException(result.error)52 is Result.Success -> data = result.get()53 }54 }55 return data56 }57 private class MultiDeserializer : ResponseDeserializable<List<Any>>58 {59 override fun deserialize(content: String): List<Any>?60 {61 val gson = Gson()62 val objectList = mutableListOf<Any>()63 val responseJson = JsonParser().parse(content).asJsonObject["results"].asJsonArray64 responseJson.forEach {65 val jsonObject = it.asJsonObject66 val mediaType = jsonObject["media_type"].asString67 when (mediaType)68 {69 "movie" -> objectList.add(gson.fromJson(it, MovieType::class.java))70 "tv" -> objectList.add(gson.fromJson(it, TvShowType::class.java))71 "person" -> objectList.add(gson.fromJson(it, PersonType::class.java))72 }73 }74 return objectList75 }76 }77 private inline fun <reified T : Any> sendRequest(url: String): T?78 {79 var data: T? = null80 url.httpGet().responseObject<T> { _, _, result ->81 when (result)82 {83 is Result.Failure -> throw TmdbGqlException(result.error)84 is Result.Success -> data = result.get()85 }86 }87 return data88 }89 private fun <T : Any> sendListRequest(url: String, params: List<Pair<String, Any?>> = emptyList()): List<T>90 {91 var data = emptyList<T>()92 url.httpGet(params).responseObject<List<T>> { _, _, result ->93 when (result)94 {95 is Result.Failure -> throw TmdbGqlException(result.error)96 is Result.Success -> data = result.get()97 }98 }99 return data100 }101}...
NetworkManager.kt
Source:NetworkManager.kt
...34 next(request, response)35 }36 }37 }38 fun ip(success: (Request, Response, String) -> Unit, failure: ((Request, Response, Exception) -> Unit)? = null): Request =39 proxy.get("https://ipecho.net/plain", success, failure)40 fun userAgent(success: (Request, Response, HttpBinUserAgent) -> Unit, failure: ((Request, Response, Exception) -> Unit)? = null): Request =41 proxy.get("https://httpbin.org/user-agent", success, failure).cache(success)42 .authenticate("john", "doe")43 .body("42")44 // If coming from cache, response.isSuccessful will be false45 private inline fun <reified T: Any> Request.cache(crossinline success: (Request, Response, T) -> Unit): Request {46 response { request, response, result ->47 val key = request.url.toString()48 result.fold({ data ->49 cache.put(key, data)50 Logger.debug("Caching as '$key'")51 }, {52 cache.get(key)?.let { byteArray ->53 val data = (byteArray as ByteArray).toString(Charset.defaultCharset())54 proxy.deserialize<T>(data)?.let { t ->55 success(request, response, t)...
QrScanResultDialog.kt
Source:QrScanResultDialog.kt
1package com.example.easyin2import android.app.Dialog3import android.content.Context4import kotlinx.android.synthetic.main.qr_result_dialog.*5import com.github.kittinunf.fuel.Fuel6import com.github.kittinunf.fuel.core.FuelError7import com.github.kittinunf.fuel.core.Request8import com.github.kittinunf.fuel.core.Response9import com.github.kittinunf.fuel.core.awaitResult10import com.github.kittinunf.fuel.core.extensions.jsonBody11import com.github.kittinunf.fuel.httpGet12import com.github.kittinunf.fuel.httpPost13import com.github.kittinunf.fuel.json.jsonDeserializer14import com.github.kittinunf.fuel.json.responseJson15import com.github.kittinunf.result.Result;16import org.json.JSONObject17import kotlin.reflect.typeOf18class QrScanResultDialog(var context : Context) {19 private lateinit var dialog: Dialog20 private var qrResultUrl : String = ""21 var email : String = ""22 init {23 initDialog()24 }25 private fun initDialog() {26 dialog = Dialog(context)27 dialog.setContentView(R.layout.qr_result_dialog)28 dialog.setCancelable(false)29 Onclicks()30 }31 fun show(qrResult: String) {32 qrResultUrl = qrResult33 dialog.scannedText.text = qrResultUrl34 email = qrResultUrl35 dialog.show()36 }37 private fun Onclicks() {38 dialog.postResult.setOnClickListener {39 postResult(qrResultUrl)40 }41 dialog.cancelDialog.setOnClickListener {42 dialog.dismiss()43 }44 }45// Adding an identity to the system46private fun postResult(Url: String) {47 val dataPOST = JSONObject()48 dataPOST.put("email", email)49 println(dataPOST)50 "http://oneeasyin.com:8080/identity/postidentity"51 .httpPost()52 .header("Content-Type" to "application/json")53 .body(dataPOST.toString()).responseJson {54 request, response, result ->55 when (result) {56 is Result.Failure -> {57 val ex = result.getException()58 println(ex)59 }60 is Result.Success -> {61 val data = result.get().obj()62 println(data)63 }64 }65 }66 }67 }...
ApiService.kt
Source:ApiService.kt
1package com.example.kotlintestapp.auth2import android.content.ContentValues3import android.util.Log4import com.github.kittinunf.fuel.core.extensions.authentication5import com.github.kittinunf.fuel.httpGet6import com.github.kittinunf.fuel.httpPost7import com.github.kittinunf.result.Result8import com.google.gson.Gson9import java.lang.Exception10class ApiService {11 private val clientId = "" //add clientId12 private val clientSecret = "" //add clientSecret13 private val apigeeTokenUrl = "" //add token url14 private val grantType = "client_credentials"15 var token: String? = null16 var tokenType: String? = null17 private fun callApi(apiEndpoint: String, tokenType: String, token: String): Any {18 val (request, response, result) = apiEndpoint19 .httpGet()20 .header(Pair("Authorization", "$tokenType $token"))21 .responseString()22 return when (result) {23 is Result.Success -> {24 Log.d(ContentValues.TAG, "Success ${result.value}")25 }26 is Result.Failure -> {27 Log.d(ContentValues.TAG, "Failed")28 }29 }30 }31 private fun setAuthToken() {32 try {33 val (request, response, result) = apigeeTokenUrl.httpPost(listOf(34 "grant_type" to grantType,35 ))36 .authentication().basic(clientId, clientSecret)37 .responseString()38 when (result) {39 is Result.Success -> {40 var gson = Gson()41 val tokenResultJson = gson.fromJson(result.value, AuthResult::class.java)42 token = tokenResultJson!!.access_token!!43 tokenType = tokenResultJson!!.token_type!!44 Log.d(ContentValues.TAG, "token $token")45 Log.d(ContentValues.TAG, "token type $tokenType")46 }47 is Result.Failure -> {48 // handle error49 println("error")50 }51 }52 }catch (e: Exception){53 e.printStackTrace()54 }55 }56 init {57 setAuthToken()58 callApi("https://..../getUsers", tokenType!!, token!!)59 }60}...
WebAppStatusCheckerTest.kt
Source:WebAppStatusCheckerTest.kt
...25 fun checkStatusTestReturnFailureWhenGetOfNonExistingUrl() {26 val nonExistingUrl = "http://non.existing.url"27 Mockito.reset(mockHttpClient)28 Mockito.`when`(mockHttpClient.get(nonExistingUrl))29 .thenReturn(Triple(mockRequest, mockResponse, Result.Failure(FuelError(Exception("failure")))))30 val res = statusChecker.checkStatus(nonExistingUrl)31 Assert.assertEquals("Status checker should return failure when the url does not exist", LoadStatus.LOADING, res)32 }33}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!