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

查看:55
本文介绍了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).第一次调用必须调用真正的方法.有没有办法做到这一点?

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天全站免登陆