Mockito如何仅模拟超类方法的调用 [英] Mockito How to mock only the call of a method of the superclass

查看:245
本文介绍了Mockito如何仅模拟超类方法的调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些测试中,我正在使用Mockito.

I'm using Mockito in some tests.

我有以下课程:

class BaseService {  
    public void save() {...}  
}

public Childservice extends BaseService {  
    public void save(){  
        //some code  
        super.save();
    }  
}   

我只想模拟ChildService的第二个调用(super.save).第一次调用必须调用real方法.有办法吗?

I want to mock only the second call (super.save) of ChildService. The first call must call the real method. Is there a way to do that?

推荐答案

否,Mockito不支持此功能.

No, Mockito does not support this.

这可能不是您要寻找的答案,但是您看到的是不应用设计原则的症状:

This might not be the answer you're looking for, but what you're seeing is a symptom of not applying the design principle:

偏爱继承而非继承

如果您提取策略而不是扩展超类,那么问题就解决了.

If you extract a strategy instead of extending a super class the problem is gone.

但是,如果不允许您更改代码,但无论如何都必须对其进行测试,并且以这种尴尬的方式,仍然存在希望.使用某些AOP工具(例如AspectJ),您可以将代码编织到超类方法中,而完全避免执行(糟糕).如果使用代理,则无法使用,必须使用字节码修改(加载时编织或编译时编织).也有支持这种技巧的模拟框架,例如PowerMock和PowerMockito.

If however you are not allowed to change the code, but you must test it anyway, and in this awkward way, there is still hope. With some AOP tools (for example AspectJ) you can weave code into the super class method and avoid its execution entirely (yuck). This doesn't work if you're using proxies, you have to use bytecode modification (either load time weaving or compile time weaving). There are be mocking frameworks that support this type of trick as well, like PowerMock and PowerMockito.

我建议您进行重构,但是如果这不是一种选择,那么您将获得一些严肃的黑客乐趣.

I suggest you go for the refactoring, but if that is not an option you're in for some serious hacking fun.

这篇关于Mockito如何仅模拟超类方法的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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