如何判断对象是否为Mockito模拟? [英] How can I tell if an object is a Mockito mock?

查看:121
本文介绍了如何判断对象是否为Mockito模拟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过代码判断给定对象是否是Mockito模拟?

Is it possible to tell in code if a given object is a Mockito mock or not?

我要执行此操作的原因是在使用模拟时返回不同的错误消息.这将用于向其他开发人员建议他们应该使用预先设置的模拟程序,该模拟程序已经设置为以有用的方式应答呼叫,而不是自己创建模拟程序.

The reason I'd like to do this is to return a different error message when a mock is being used. This would be used to suggest to other developers that they should use a pre-prepared mock that is already set to answer calls in a useful way rather than creating the mock themselves.

目前我所能拥有的最好的是object.getClass().getName().contains("EnhancerByMockitoWithCGLIB"),但这感觉很hacky.

At the moment the best I have is object.getClass().getName().contains("EnhancerByMockitoWithCGLIB") but this feels hacky.

推荐答案

好像没有这样的API(请提出一个问题,应该这样!)幸运的是(在下面的注释中)包裹:

Looks like there is no such API (please raise an issue, it should be!) Fortunately (following your comment below) there is a method in the org.mockito.internal.util package:

import org.mockito.internal.util.MockUtil;

new MockUtil().isMock(obj)

将来可能会在公共API中添加Mockito.isMock()方法,请参见:问题313:在org.mockito.internal之外提供isMock)..

In the future Mockito.isMock() method might be added to public API, see: Issue 313: Provide isMock outside of org.mockito.internal).

这篇关于如何判断对象是否为Mockito模拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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