首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >cglib如何修复spock中的模拟问题

cglib如何修复spock中的模拟问题
EN

Stack Overflow用户
提问于 2021-07-14 16:27:44
回答 1查看 64关注 0票数 0

我下课了

代码语言:javascript
复制
class TestClientSpec extends Specification {

    TestClient testClient
    RestTemplate restTemplate

    def setup() {
        restTemplate = Mock()
        testClient = new TestClient(restTemplate)
    }

    def 'successful'() {
    
        given:
        def url = 'https://test123'
     
        when:
        testClient.getValue(url)

        then:
        1 * restTemplate.getForEntity(url, Test.class)
    }
}

当我尝试运行此测试时,出现以下错误

代码语言:javascript
复制
Cannot create mock for class org.springframework.web.client.RestTemplate. Mocking of non-interface types requires a code generation library. Please put an up-to-date version of byte-buddy or cglib-nodep on the class path.
org.spockframework.mock.CannotCreateMockException: Cannot create mock for class org.springframework.web.client.RestTemplate. Mocking of non-interface types requires a code generation library. Please put an up-to-date version of byte-buddy or cglib-nodep on the class path.

之后,我添加了cglib依赖,它工作得很好

implementation group: 'cglib', name: 'cglib-nodep', version: '3.3.0'

但是不确定为什么会抛出上面的错误,以及cglib如何修复这个错误?

EN

回答 1

Stack Overflow用户

发布于 2021-07-14 21:49:00

Spock使用字节码生成器库( cglibbyte-buddy )在运行时生成类,以便能够模拟类。

对这些库的依赖是可选的,这样你就可以选择是否使用它们,因为你可以使用一些专用的模拟库来满足你的所有模拟需求(例如PowerMock)。

如何在类路径中添加字节码库来解决这个问题?

好吧,通过在Spock中启用必要的代码...如果是Cglib,则为CglibMockFactory

Spock似乎在MockInstantiator上发现了哪个库可用于模拟...如果你了解Java反射,做这样的事情并不难,只要做一些像Class.forName("org.objenesis.Objenesis")这样的事情,如果它没有抛出ClassNotFoundException,你可以使用它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68374574

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档