【问题标题】:Spock Testing got NoClassDefFoundError: net/bytebuddy/TypeCache when Mocking RestTemplateSpock 测试在 Mocking RestTemplate 时得到 NoClassDefFoundError: net/bytebuddy/TypeCache
【发布时间】:2019-02-06 23:09:00
【问题描述】:

我正在测试我的 DAO 类,该类使用扩展 RestTemplate 的自定义 RestTemplate 来执行 postForObject,但即使在我将字节伙伴依赖项添加到 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 )
    }
} 
*/
}

【问题讨论】:

  • 你添加了哪个 bytebuddy 依赖?
  • @tim_yates 我刚刚用依赖更新了帖子
  • Spock 的哪个版本?
  • 那个版本的 bytebuddy 太旧了
  • Ahhh Szymon 你在下面介绍过吗????

标签: spring groovy spock


【解决方案1】:

TypeCache&lt;T&gt; 类是在 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 依赖版本更新为以下之一,它应该可以解决您的问题。

【讨论】:

  • 使用更新版本的 byte-buddy 解决了我的问题。非常感谢@Szymon Stepniak
  • 是的,例如org.springframework.boot:spring-boot-starter-test2.0.2.RELEASE 版本取决于 mockito-core2.15.0 版本,这取决于 1.7.9 的版本byte-buddy 对于 spock-core 版本不够新 1.2+-groovy-2.4
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-12
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
相关资源
最近更新 更多