使用 spring-retry 进行 SpringBoot 测试

问题描述

我有以下功能(该功能并不重要):

    fun myRandomFunc(something: String?): List<Int> {
        return listof(5)
    }

你可以想象它正在执行一些 API 调用,返回一些对象的列表等。我可以在测试中轻松地模拟这个函数,如下所示:

        doReturn(
            listof(
                5
            )
        )
            .whenever(...).myRandomFunc("something")

但是在我在混合中引入(重试/恢复)之后,该模拟现在正在抛出 org.mockito.exceptions.misusing.NotAMockException at ...。知道为什么吗?

这是带有弹簧重试的代码

    @Retryable(
        value = [ApiException::class],maxAttempts = MAX_RETRIES,backoff = Backoff(delay = RETRY_DELAY,multiplier = RETRY_MULTIPLIER,random = true)
    )
    fun myRandomFunc(something: String?): List<Int> {
        return listof(5)
    }

    @Recover
    fun testMyRandomFunc(exception: Exception): List<Int> {
        log.error("Exception occurred ...",exception)
        throw RemoteServiceNotAvailableException("Call Failed after $MAX_RETRIES retries")
    }

代码有效,功能正常,只是测试的模拟现在被破坏了。希望得到一些帮助

解决方法

Spring retry 在对象周围创建一个代理。

如果有接口,则代理为JDK代理;如果不是,则使用 CGLIB。

Mockito 不能模拟 CGLIB (final) 方法。