Mockk, Kotest - How to test reactive subscribe onError callback?

69 views Asked by At

I have this simple function calling http request

    override fun refreshDocument(
        investmentIntermediary: InvestmentIntermediary,
        receivedDocumentUuid: String
    ) {
        if (investmentIntermediary.webhookUrl != null) {
            val slash = if (investmentIntermediary.webhookUrl.endsWith("/")) "" else "/"
            httpClient.exchange(
                HttpRequest.PUT(
                    "${investmentIntermediary.webhookUrl}$slash$receivedDocumentUuid", null
                )
            ).subscribe(object : Subscriber<Any> {
                override fun onSubscribe(subscription: Subscription) = subscription.request(1)
                override fun onError(t: Throwable) = logger.error("Error when invoking refresh document webhook", t)
                override fun onComplete() = Unit
                override fun onNext(message: Any) = Unit
            })
        }
    }

I need to test onError method, that will log the error. I use kotest with mockk

Tried this:


    "Logs error when refresh fail" {
        val mockHttpClient: HttpClient = mockk(relaxed = true)
        val mockLogger: Logger = mockk(relaxed = true)
        val testError = RuntimeException("Test error")

        every {
            mockHttpClient.exchange(any()).subscribe(any())
        } answers {
            val subscriber = arg<Subscriber<Any>>(1)
            subscriber.onError(testError)
        }
        with(getMock(investmentIntermediaryService)) {
            verify(timeout = 5000, exactly = 0) {
                refresh(any(), any())
            }

            verify {
                mockLogger.error("Error when invoking refresh document webhook", testError)
            }
        }
    }

How generally I can test the callback functions?

0

There are 0 answers