Spock Testing got NoClassDefFoundError: net/bytebu

2019-08-19 12:26发布

问题:

I am testing my DAO class which uses a custom RestTemplate that extends RestTemplate to do postForObject, but I am getting the below error even after I added byte-buddy dependency to pom.xml. This error seems happening on the call to Mock(). Can someone please let me know what I did wrong?

 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>       

My Dao class:

@Component
public class DaoClass {

   @Autowired
   private MyCustomRestTemplate restTemplate;

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

I have set up a TestConfiguration class so that the test restTemplate bean will be used in testing:

    @Configuration
    public class TestConfiguration {

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

Here is my Spock code where I mocked 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:

The TypeCache<T> class was introduced in byte-buddy 1.6.0, so you need this version at the minimum. Spock uses optional byte-buddy dependency, which means that the version you specified in your pom.xml takes precedence. Depending on the Spock version, here are byte-buddy versions used by a specific Spock version:

  • spock-core:1.2-groovy-2.4 => byte-buddy:1.8.21
  • spock-core:1.1-groovy-2.4 => byte-buddy:1.6.5

Update byte-buddy dependency version to one of the following and it should fix your problem.