为什么 Mockito 不模拟静态方法? [英] Why doesn't Mockito mock static methods?

查看:59
本文介绍了为什么 Mockito 不模拟静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里阅读了一些关于静态方法的主题,我想我理解误用/过度使用静态方法可能导致的问题.但是我并没有真正了解为什么很难模拟静态方法.

I read a few threads here about static methods, and I think I understand the problems misuse/excessive use of static methods can cause. But I didn't really get to the bottom of why it is hard to mock static methods.

我知道其他模拟框架,如 PowerMock,可以做到这一点,但为什么 Mockito 不能?

I know other mocking frameworks, like PowerMock, can do that but why can't Mockito?

我阅读了这篇文章,不过作者似乎对static这个词很反感,可能是我的理解太差了.

I read this article, but the author seems to be religiously against the word static, maybe it's my poor understanding.

一个简单的解释/链接会很棒.

An easy explanation/link would be great.

推荐答案

我认为原因可能是模拟对象库通常通过在运行时动态创建类来创建模拟(使用 cglib).这意味着它们要么在运行时实现一个接口(如果我没记错的话,这就是 EasyMock 所做的),或者它们从类继承来模拟(如果我没记错的话,这就是 Mockito 所做的).这两种方法都不适用于静态成员,因为您不能使用继承来覆盖它们.

I think the reason may be that mock object libraries typically create mocks by dynamically creating classes at runtime (using cglib). This means they either implement an interface at runtime (that's what EasyMock does if I'm not mistaken), or they inherit from the class to mock (that's what Mockito does if I'm not mistaken). Both approaches do not work for static members, since you can't override them using inheritance.

模拟静态的唯一方法是在运行时修改一个类的字节码,我认为这比继承要复杂一些.

The only way to mock statics is to modify a class' byte code at runtime, which I suppose is a little more involved than inheritance.

这是我的猜测,它的价值...

That's my guess at it, for what it's worth...

这篇关于为什么 Mockito 不模拟静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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