我下课了
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)
}
}当我尝试运行此测试时,出现以下错误
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如何修复这个错误?
发布于 2021-07-14 21:49:00
Spock使用字节码生成器库( cglib或byte-buddy )在运行时生成类,以便能够模拟类。
对这些库的依赖是可选的,这样你就可以选择是否使用它们,因为你可以使用一些专用的模拟库来满足你的所有模拟需求(例如PowerMock)。
如何在类路径中添加字节码库来解决这个问题?
好吧,通过在Spock中启用必要的代码...如果是Cglib,则为CglibMockFactory。
Spock似乎在MockInstantiator上发现了哪个库可用于模拟...如果你了解Java反射,做这样的事情并不难,只要做一些像Class.forName("org.objenesis.Objenesis")这样的事情,如果它没有抛出ClassNotFoundException,你可以使用它。
https://stackoverflow.com/questions/68374574
复制相似问题