spring - Spock 测试在 Mocking RestTemplate 时得到 NoClassDefFoundError: net/bytebuddy/TypeCache
问题描述
我正在测试我的 DAO 类,该类使用扩展 RestTemplate 来执行 postForObject 的自定义 RestTemplate,但即使在我将字节伙伴依赖项添加到 pom.xml 之后,我也会收到以下错误。这个错误似乎发生在对 Mock() 的调用上。有人可以让我知道我做错了什么吗?
NoClassDefFoundError: net/bytebuddy/TypeCache
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.3.16</version>
<scope>test</scope> <!--also tried giving "runtime" here -->
</dependency>
我的道课:
@Component
public class DaoClass {
@Autowired
private MyCustomRestTemplate restTemplate;
public SomeObjectType getAddressFromSomewhere(
String url, String request) {
......
return restTemplate.postForObject(url, request, SomeObjectType.class);
}
}
我已经设置了一个 TestConfiguration 类,以便在测试中使用测试 restTemplate bean:
@Configuration
public class TestConfiguration {
@Bean
public MyCustomRestTemplate restTemplate() {
return new MyCustomRestTemplate();
}
}
这是我模拟 restTemplate postForObject 的 Spock 代码:
@ContextConfiguration(classes = [TestConfiguration.class])
@Import([DaoClass.class])
public class TestDao extends Specification {
@Autowired
private DaoClass dao;
//got the same error regardless of using @SpringBean or @TestConfiguration
@SpringBean
MyCustomRestTemplate restTemplate = Mock() //***** Error occurred here
def "Test Success Senario"() {
def obj = .... // get object
given: "rest template"
1 * restTemplate.postForObject(_, _, _) >> obj
when: "we call Dao"
def actualResponse = dao.getAddressFromSomewhere(_);
then: "we get response"
actualResponse == obj
}
// got the same error regardless of using @SpringBean or @TestConfiguration
/*
@TestConfiguration
static class MockConfig {
def detachedMockFactory = new DetachedMockFactory()
@Bean
MyCustomRestTemplate restTemplate() {
return detachedMockFactory.Mock(MyCustomRestTemplate )
}
}
*/
}
解决方案
该类TypeCache<T>
是在 byte-buddy 1.6.0 中引入的,因此您至少需要此版本。Spock 使用可选的 byte-buddy 依赖,这意味着您在 pom.xml 中指定的版本优先。根据 Spock 版本,以下是特定 Spock 版本使用的字节伙伴版本:
- spock-core:1.2-groovy-2.4 => byte-buddy:1.8.21
- spock-core:1.1-groovy-2.4 => byte-buddy:1.6.5
将 byte-buddy 依赖版本更新为以下之一,它应该可以解决您的问题。
推荐阅读
- sqlite - 查询将行转换为列 SQLite
- c# - 是否可以在 autofac 中使用某种动态 KeyFilter?
- powershell - vNext 解决非域机器上的第二跳问题
- r - 计算R中连续类别变化的时间条纹数
- angular - 如何跨模块创建 HttpInterceptor?
- c# - 如何在用户控件中将互斥的 MenuItems 与互斥的单选按钮绑定
- c++builder - 两个 TMemo 对象共享一个 TPopupMenu
- python - 从匹配对象获取模式匹配
- java - 替代 lambda
- django - GraphQL AttributeError:模块“石墨烯”没有属性“英雄”