sam*_*ach 6 java integration-testing mocking mockito cglib
mockito无法模拟已经由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();
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,doNothing().when(articleMock).extractImages();
它实际上调用了真正的函数.仔细看看articleMock会增强两次.造成这种情况的autowiring
原因之一spying
.
如果我不能监视enhaced对象,那么我如何getArticle()
在Integration测试中测试该方法,以便我可以验证是否返回了正确的DTO.
注意:我实际上不想测试执行文件系统调用的方法.只是DB的.这就是为什么我需要测试该getArticle
方法.
如果我理解正确的话,你的类是由 Spring 连接的。仅当没有由对象实现的接口时,Spring 才使用 CGLIB 来确保事务行为。如果有接口,它会使用简单的 JDK 动态代理。(参见http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch08s06.html)
也许你可以尝试提取一个接口,并让Spring使用动态代理。也许那时 Mockito 可以表现得更好。