Mockito 如何仅模拟超类方法的调用

Mockito How to mock only the call of a method of the superclass(Mockito 如何仅模拟超类方法的调用)
本文介绍了Mockito 如何仅模拟超类方法的调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我在一些测试中使用了 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 如何仅模拟超类方法的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)