简体   繁体   English

类中的Mockito和final equals()方法-是否可模拟?

[英]Mockito and final equals() method in class - is it mockable?

I want to mock a class from other library using Mockito. 我想使用Mockito从其他库中模拟一个类。 I read that Mockito relies on specific (CGLIB provided I think) implementation of equals method. 我读到Mockito依赖于equals方法的特定实现(我认为是CGLIB)。 Unfortunately this outer class has equals() denoted with final modifier, and there is throwing exception in its body. 不幸的是,这个外部类具有用final修饰符表示的equals(),并且其主体中存在抛出异常。

When I try to mock this class I always get exception from this method. 当我尝试模拟此类时,总是会从此方法获取异常。 CGLIB apparently doesn't get by with final, and real method is called. CGLIB显然不能通过final来实现,而是调用了真正的方法。

Any ideas? 有任何想法吗? What can I do, to mock this class using Mockito? 我该怎么做,以使用Mockito模拟此类? Maybe other library will handle it? 也许其他图书馆会处理吗?

[EDIT] quick explanation: I don't want to mock equals(), I check other methods. [编辑]快速说明:我不想模拟equals(),我检查其他方法。 Problem is that mockito internally uses equals(), I don't know what for. 问题是,mockito内部使用equals(),我不知道该做什么。 As equals() is final, real method is called with exception throwing. 由于equals()是最终的,因此将实际方法调用并引发异常。 I had hope that there is some setting in mockito "don't use equals()" :-) Thanks for answers, I will read them closely tomorrow. 我曾希望在嘲笑中有一些设置“不要使用equals()” :-)感谢您的回答,我明天会仔细阅读它们。

This matrix shows features supported by different frameworks: 此矩阵显示了不同框架支持的功能: 模拟框架功能比较

External link to the matrix here . 外部链接到这里的矩阵。

According to this, only PowerMock and JMockit can mock final methods. 据此,只有PowerMockJMockit可以模拟最终方法。

Mockito cannot mock final methods. Mockito无法模拟最终方法。 Apparently PowerMock can though. 显然, PowerMock可以。

A hacky workaround could be to create a non-final method that delegates to the final equals method and mock that. 一个变通的解决方法是创建一个非最终方法,该方法委派给最终的equals方法并对其进行模拟。

I believe that the steps to mock a final method with PowerMock and Mockito API would be: run your tests with the @RunWith(PowerMockRunner.class) then prepare the class you want to mock @PrepareForTest(ClassToBeMocked.class) . 我相信使用PowerMock和Mockito API模拟最终方法的步骤将是:使用@RunWith(PowerMockRunner.class)运行测试,然后准备要模拟@PrepareForTest(ClassToBeMocked.class) After that, mock your object and use the when method to mock the equals method. 之后,模拟对象并使用when方法模拟equals方法。

I think that it won't work if you do not use the PrepareForTest annotation in your test class. 我认为,如果您在测试类中不使用PrepareForTest批注,它将无法正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM