模拟CGLIB增强对象 [英] Mocking CGLIB enhanced objects

查看:158
本文介绍了模拟CGLIB增强对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mockito无法模拟已经由CGLIB增强的对象吗?

Is it true that mockito can't mock objects that were already enhanced by CGLIB?

public class Article {

     @Autowired
     private dbRequestHandler

     @Autowired
     private filesystemRequestHandler

     @Transactional
     public ArticleDTO getArticleContents() {

         //extractText() and then save the data in DTO
         //extractImages() and then save the data in DTO
         // some other calls to other databases to save data in dto

       return articleDTO;

     }
     public void extractText() {

        //call to DB

   }

   public void extractImages() {

        // call to file system

   }
}


public class IntegrationTest {

  @Autowired
  private Article article;

  //setup method {

  articleMock = Mockito.spy(article);

  doNothing().when(articleMock).extractImages();
 }
}

在上面的示例中,当谈到<$ c时$ c> doNothing()。when(articleMock).extractImages(); 它实际上调用了真正的函数。仔细看看articleMock会增强两次。导致自动装配的原因之一是间谍的第二次原因。

In the above example when it comes to doNothing().when(articleMock).extractImages(); it actually calls the real function. On a closer look articleMock gets enhanced two times. One cause of autowiring and second time cause of spying.

如果我不能监视增强的对象,那么如何测试我的 getArticle()方法集成测试,以便我可以验证是否返回了正确的DTO。

If I can't spy on enhaced objects, then how can I test the getArticle() method in my Integration test, so that I can verify a proper DTO is returned.

注意:我实际上不想测试执行文件系统调用的方法。只是DB的。这就是为什么我需要测试 getArticle 方法。

Note : I actually don't want to test the method which does filesystem calls. just the DB ones. thats why I need to test the getArticle method.

推荐答案

如果我正确理解你的课程是由Spring连接的。 Spring仅在没有由对象实现的接口时才使用CGLIB来确保事务行为。如果有接口,它使用简单的JDK动态代理。 (参见 http://docs.spring.io /spring/docs/3.0.0.M3/reference/html/ch08s06.html

If I understand correctly your class is wired by Spring. Spring uses CGLIB to ensure transactional behaviour only if there is no interface, which is implemented by your object. If there is an interface, it uses simple JDK Dynamic Proxies. (see http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch08s06.html)

也许你可以尝试提取一个接口,然后让Spring使用动态代理。也许那么Mockito可以表现得更好。

Maybe you could try to extract an interface, and let Spring to use dynamic proxies. Maybe then Mockito could perform better.

这篇关于模拟CGLIB增强对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆