简体   繁体   English

使用Mockito调用super.method()

[英]Verifying super.method() is called using Mockito

First of all I would like to say I am working with legacy code and I cannot change it no matter how much I want to. 首先,我想说我正在使用遗留代码,无论我想要多少,我都无法改变它。

With that out the way, what I am trying to do is verify that a super.method() is called. 顺便说一句,我要做的是验证是否调用了super.method()。 This is specifically what I am trying to test with Mockito/Junit: 这是我试图用Mockito / Junit测试的具体内容:

class foo extends JApplet(){

       public void destroy(){
          super.destroy();
 }
}

Normally something like this would suffice in a test case if it was not a super method being called: 通常情况下,如果这不是一个被调用的超级方法,那么在测试用例中就足够了:

verify(foo).destroy();

I've seen this question asked a couple of times and usually the response is "Inheritance is bad, change your code" which I cannot do at all unfortunately. 我已经看过几次问这个问题,通常回答是“继承是坏的,改变你的代码”,遗憾的是我完全不能做。 Is anyone aware of any frameworks or small little tricks I could do to test this? 是否有人知道我可以做的任何框架或小小技巧来测试这个?

Thanks in advance - I know this is a tricky problem! 提前谢谢 - 我知道这是一个棘手的问题!

You can refactor the code to call the super method in some other method like: 您可以重构代码以在其他方法中调用super方法,例如:

      class foo extends JApplet(){

       public void destroy(){
          callSuperDestroy();
       }
       public void callSuperDestroy(){
           super.destroy();
       }}

And then verify: 然后验证:

verify(foo).callSuperDestroy();

It appears that JMockit might be able to do this. 似乎JMockit可能能够做到这一点。 Check out this post: 看看这篇文章:

Powermock - mocking a super method invocation Powermock - 模拟超级方法调用

I haven't tried this, but isn't it possible to create a custom ClassLoader which overrides loading of JApplet class only? 我没试过这个,但是不可能创建一个自定义的ClassLoader,它只覆盖JApplet类的加载吗? Then you can create your own JApplet, which remembers whether destroy() is called. 然后你可以创建自己的JApplet,它记住是否调用destroy()。

What you actually need to test is that the effect of invoking the super-method still hold true. 你真正需要测试的是调用超级方法的效果仍然适用。 The fact that the easiest way to achieve this is via invoking the super-method is simply a design detail. 实现这一目标的最简单方法是通过调用超级方法,这只是一个设计细节。

With this in mind: 考虑到这一点:

  1. Write a test for the super-method. 为超级方法编写测试。
  2. Write a test for your sub-method, and also invoke the test for the super-method on the same class from within this test (either by direct invocation, or by subclassing the test). 为您的子方法编写测试,并在此测试中调用同一类的超级方法测试(通过直接调用或通过子类化测试)。

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

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