cglib 如何修复 spock 中的模拟问题
How cglib fixing the mock issue in spock
我有以下 class
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 如何解决这个问题?
Spock 使用字节码生成器库,cglib
或 byte-buddy
,在运行时生成 类,以便能够模拟 类.
对这些库的依赖是可选的,因此您可以选择是否使用它们,因为您也可以使用一些专用的模拟库来满足您的所有模拟需求(例如 PowerMock)。
如何将字节码库添加到类路径来解决这个问题?
好吧,通过在 Spock 中启用必要的代码...如果是 Cglib,CglibMockFactory。
Spock 似乎在 MockInstantiator 找到了可用于模拟的库...如果您知道 Java 反射,那么做那种事情并不难,只需做类似的事情Class.forName("org.objenesis.Objenesis")
如果没有抛出 ClassNotFoundException
你可以使用它。
我有以下 class
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 如何解决这个问题?
Spock 使用字节码生成器库,cglib
或 byte-buddy
,在运行时生成 类,以便能够模拟 类.
对这些库的依赖是可选的,因此您可以选择是否使用它们,因为您也可以使用一些专用的模拟库来满足您的所有模拟需求(例如 PowerMock)。
如何将字节码库添加到类路径来解决这个问题?
好吧,通过在 Spock 中启用必要的代码...如果是 Cglib,CglibMockFactory。
Spock 似乎在 MockInstantiator 找到了可用于模拟的库...如果您知道 Java 反射,那么做那种事情并不难,只需做类似的事情Class.forName("org.objenesis.Objenesis")
如果没有抛出 ClassNotFoundException
你可以使用它。