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

查看:162
本文介绍了为什么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在没有弄错的情况下所做的事情),或者他们从类继承到mock(这就是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天全站免登陆