Spock Testing got NoClassDefFoundError: net/bytebuddy/TypeCache when Mocking RestTemplate

Spock Testing got NoClassDefFoundError: net/bytebuddy/TypeCache when Mocking RestTemplate

我正在测试我的 DAO class,它使用扩展 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>       

我的道class:

@Component
public class DaoClass {

   @Autowired
   private MyCustomRestTemplate restTemplate;

   public SomeObjectType getAddressFromSomewhere(
       String url, String request) {
     ......
     return restTemplate.postForObject(url, request, SomeObjectType.class);     
 }
}

我已经设置了一个 TestConfiguration class 以便在测试中使用测试 restTemplate bean:

    @Configuration
    public class TestConfiguration {

        @Bean
        public MyCustomRestTemplate restTemplate() {
            return new MyCustomRestTemplate();
    }
}

这是我的 Spock 代码,我在其中模拟了 restTemplate postForObject:

@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 )
    }
} 
*/
}

字节好友1.6.0引入了TypeCache<T>class,所以你至少需要这个版本。 Spock 使用可选的字节伙伴依赖性,这意味着您在 pom.xml 中指定的版本优先。根据 Spock 版本,以下是特定 Spock 版本使用的 byte-buddy 版本:

  • 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 依赖版本更新为以下版本之一,它应该可以解决您的问题。